题目描述:
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
题目思路:
Given an array [0,4,4,0,0,2,4,4]
, value=4
return 4
and front four
elements of the array is [0,0,0,2]
这题还是用two pointer的做法,两个pointer:l和i的起始点都在数组开始。然后i一个一个往前挪动,如果A[i] != elem,就把A[l]赋值A[i],然后l往后挪一位。最后的长度就是l的值。
Mycode(AC = 15ms):
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) {
// write your code here
if (A.size() == 0) return 0;
int left = 0;
for (int i = 0; i < A.size(); i++) {
if (A[i] != elem) {
A[left++] = A[i];
}
}
return left;
}
};