题目:
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) {
for(int i = 0; i < n; i++) {
if(A[i] == elem) {
A[i] = A[n - 1];
n--;
i--;
}
}
return n;
}
};
思路:
这道题值得注意的就是,别找到相等的元素就逐个挪动到最后,这样效率很低。
简单的做好就是直接把当前数组最后的元素和要移动的元素对换位置,记录好数组当前长度及遍历到的元素位置即可。