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) { // Note: The Solution object is instantiated only once and is reused by each test case. int cnt = 0; for(int i = 0; i < n; ++i) { if(elem == A[i]) { ++cnt; } else { A[i-cnt] = A[i]; } } return n - cnt; } };
1 2 1 1 3 1 1 4
这样的话, 直接遍历一次就可以了, 每个数字只移动一次
a[i]移动的距离, 就是a[i]前面出现elem的次数