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.
题目不要求原顺序,但是其实也可以保持原顺序。
T。T我好像歧视自己的代码,总怎么看怎么不爽。。。
乱序版
class Solution {
public:
int removeElement(int A[], int n, int elem) {
int i = 0;
while (i < n) {
if (A[i] == elem) {
A[i] = A[n - 1];
--n;
}
else
++i;
}
return n;
}
};
顺序版
class Solution {
public:
int removeElement(int A[], int n, int elem) {
int num=0,i;
for(i=0;i<n;++i)
if(A[i]!=elem)A[num++]=A[i];
return num;
}
};
// blog.csdn.net/havenoidea