题目:
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.
方法一:首尾指针,若后面出现val,rear前移;前面出现val,用rear的元素填充front,然后front后移rear前移
int removeElement(vector<int>& nums, int val) {
if (nums.empty()) return 0;
int n = nums.size();
int front = 0;//从头遍历数组
int rear = n - 1;//指向新数组最后一个元素
while (front < rear){
if (nums[front] != val){
++front;
continue;
}
if (front < rear && nums[rear] == val) {
--rear;
continue;
}
nums[front] = nums[rear];//!!!front所指元素等于val且rear所指元素不等于val才能到这里,若所有元素都不等于val,就不能到这里,rear也不会减小
++front;
--rear;
}
if (nums[rear] == val) --rear;//!!!front == rear的那个元素没有判断过
return rear+1;
}
方法二:从后向前扫描,发现val就用数组最后一个元素填充,然后数组长度减一
int removeElement(vector<int>& nums, int val) {
int n = nums.size();
for(int i = n - 1; i >= 0; --i){
if(nums[i] == val){
nums[i] = nums[n-1];
--n;
}
}
return n;
}
方法三:从前向后扫描,endNew指向新数组最后一个元素的下一个元素,发现非val元素就用其填充endNew,然后endNew后移一位
int removeElement(vector<int>& nums, int val) {
int endNew = 0;
for(int i = 0; i < nums.size(); ++i){
if(nums[i] != val){
nums[endNew++] = nums[i];
}
}
return endNew;
}