Remove Element
题目:
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]
分析:
这道题目有一个corner case,就是说当只有一个element的时候,根本进不了循环
two pointer的题目while的退出条件总应该是start <= end而不是单纯的 <
解法:
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
int start = 0;
int end = A.size() - 1;
while (start <= end) {
if (A[start] == elem) {
int temp = A[start];
A[start] = A[end];
A[end] = temp;
end--;
} else {
start++;
}
}
return start;
}
};