zero, description
Topic link: 27. Remove elements
1. Idea:
First of all, I want to use two pointers, the left pointer goes from beginning to end, and the right goes from tail to head.
When the left pointer points to arr[ i ] != target, record the index L, and the
right pointer starts from the end to the beginning, when arr[ j ]==target, record the index R.
int removeElement(vector<int>& nums, int val) {
int N=nums.size();
int l=0,r=N-1; //存储下一次循环的地点
if(N==0) return {
};
for(int i=l;i<r;i++){
if(nums[i]==val){
l=i+1; //留作下次开始
for(int j=r;j>=i;j--){
if(nums[j]!=val){
r=j-1;
nums[i]=nums[j];
break;
}
}
}
}
return l+1;
}
When inputting nums=[1] val=1, the correct result is [ ], but the result returned by the code is [1]
Two, reference
/**
* 相向双指针方法,基于元素顺序可以改变的题目描述改变了元素相对位置,确保了移动最少元素
* 时间复杂度:O(n)
* 空间复杂度:O(1)
*/
int removeElement(vector<int>& nums, int val) {
int leftIndex = 0;
int rightIndex = nums.size() - 1;
while(leftIndex<=rightIndex){
// 找左边等于val的元素
while (leftIndex <= rightIndex && nums[leftIndex] != val){
++leftIndex;
}
//跳出while时候,leftIndex表示此时左边等于val的元素
// 找右边不等于val的元素
while (leftIndex <= rightIndex && nums[rightIndex] == val) {
-- rightIndex;
}
//跳出while时候,leftIndex表示此时右边不等于val的元素
// 将右边不等于val的元素覆盖左边等于val的元素
if (leftIndex < rightIndex) {
nums[leftIndex++] = nums[rightIndex--];
}
}
return leftIndex; // leftIndex一定指向了最终数组末尾的下一个元素
}
};
example
nums = [3,2,2,3], val = 3
leftIndex=0, rightIndex=3
nums[ leftIndex=0 ] == val, leftIndex=0
nums[ rightIndex=3 ] == val, rightIndex=2
nums[ rightIndex=2]! = val Jump out of while
to the end if, at this time leftIndex=0, rightIndex=2 exchange to get nums = [2,2,3,3]
Summarize
- Use while instead of for
- The while implementation is also the function of stopping the left pointer in the if condition