Remove Element
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.
注意:题目只要求前面的几个值是对的就行,不要求整个数列都对
返回的是新的array,不是长度。。写的有点复杂
class Solution {
public:
int removeElement(int A[], int n, int elem) {
vector<int> B;
int answer=n;
for(int i=0;i<n;i++)
{
if (A[i]==elem)
answer--;
else
B.push_back(A[i]);
}
int *C=(int*)malloc(B.size()*sizeof(int));
for(int j=0;j<B.size();j++)
{
C[j]=B[j];
cout<<C[j]<<endl;
}
return *C;
}
};
网上双指针的idea:
class Solution {
public:
int removeElement(int A[], int n, int elem) {
int answer=0;
for(int i=0;i<n;i++)
{
if (elem!=A[i])
A[answer++]=A[i];
}
return answer;
}
};