题目:
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.
思路:发现需要remove的元素直接用最后一个元素覆盖。
class Solution {
public:
int removeElement(int A[], int n, int elem) {
for (int i = 0; i < n;) {
if (A[i] == elem) {
A[i] = A[n-1];
n--;
} else {
i++;
}
}
return n;
}
};
总结:时间复杂度O(n).