- Remove Element
中文English
Given an array and a value, remove all occurrences of that value in place and return the new length.
The order of elements can be changed, and the elements after the new length don’t matter.
Example
Example 1:
Input: [], value = 0
Output: 0
Example 2:
Input: [0,4,4,0,0,2,4,4], value = 4
Output: 4
Explanation:
the array after remove is [0,0,0,2]
解法1:
双指针,一次循环,in-place操作。
代码如下:
class Solution {
public:
/*
* @param A: A list of integers
* @param elem: An integer
* @return: The new length after remove
*/
int removeElement(vector<int> &A, int elem) {
int N = A.size();
int p1 = 0, p2 = N - 1;
int result = 0;
while(p1 < p2) {
while (A[p1] != elem && p1 < p2) {
p1++;
}
if (p1 >= p2) return N - result;
result++;
while (A[p2] == elem && p1 < p2) {
result++;
p2--;
}
if (p1 >= p2) return N - result;
swap(A[p1], A[p2]);
p1++; p2--;
}
return N - result;
}
};