1.题目描述
Given an array and a value, remove all instances of that value in place and return the new length.
The order of elements can be changed. It doesn’t matter what you leave beyond the new length.
大致题意是:给定一个数组和一个值,移除数组中所有和这个值想用的元素,返回新长度。元素的顺序可以改变,你离开新的长度并不重要。
2.解题思路
本来我的解题思路和之前有一道题——remove-duplicates-from-sorted-array(从排序数组中删除重复项)一样,想定义两个变量i,j做索引值,j指向数组中下标为0的位置,i指向数组中下标为1的位置:当A[i]!=elem的时候,i和j同时向后走A[j]=A[i],否则i向后走;进行循环。 最后返回j的值作为数组长度,但是只通过了16%的测试用例。
所以我就想,如果A[i]==elem,就把这个数和数组最后一个数换一下swap(A[i],A[n-1]),数组长度n–,i–最后返回数组长度n。
3.实现代码
class Solution {
public:
int removeElement(int A[], int n, int elem) {
if(n<=0)return 0;
int i=0,j=0;
for(i=0;i<n;++i)
{
if(A[i]==elem)
{
swap(A[i],A[n-1]);
n--;
i--;
}
}
return n;
}
};