Remove Element
My SubmissionsGiven 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) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if (n < 1)
return 0;
int k = 0;
for (int i = 0; i < n; ++i) {
if (A[i] != elem ) {
swap (A[i - k], A[i]);
}
else {
++k;
}
}
return n - k;
}
};