题目
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.
思路一
向后替换
class Solution {
public:
int removeElement(int A[], int n, int elem) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(n<=0)
return n;
int newlen = n;
for(int i=0;i<newlen;i++)
{
if(A[newlen-1]!=elem)
{
if(A[i]==elem)
{
A[i] = A[newlen-1];
newlen--;
}
}
else
{
newlen--;
i--;
}
}
return newlen;
}
};
思路二
k记录前面要插入的位置,将A[i]替换到前面k位置。
class Solution {
public:
int removeElement(int A[], int n, int elem) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int k = 0;
for(int i=0;i<n;i++)
if(A[i]!=elem)
A[k++]=A[i];
return k;
}
};