当前位置:网站首页>2022-7-6 Leetcode27. Remove the element - I haven't done the problem for a long time. It's such an embarrassing day for double pointers

2022-7-6 Leetcode27. Remove the element - I haven't done the problem for a long time. It's such an embarrassing day for double pointers

2022-07-07 13:38:00 weixin_ fifty-one million one hundred and eighty-seven thousand

 Insert picture description here
 Insert picture description here

class Solution {
    
public:
    int removeElement(vector<int>& nums, int val) {
    
        int leftIdx = 0;
        int rightIdx = nums.size()-1;
        while (leftIdx <= rightIdx){
    
            while (leftIdx <= rightIdx && nums[leftIdx] != val){
    
                leftIdx++;
                
            }
            while (leftIdx <= rightIdx&& nums[rightIdx] == val){
    
                rightIdx--;
                
            }
            if (leftIdx < rightIdx)
            nums[leftIdx++] = nums[rightIdx--];
        }
        return leftIdx;
    }
};

Two points to pay attention to :
1)while (leftIdx < nums.size() && nums[leftIdx++] != val);
You can't write it like that , Because if the current !=val, It will also move forward one
2) And can't write leftIdx < nums.size().
Because it's possible rightIdx The following numbers are val, But the pointer on the right has moved to the front .

原网站

版权声明
本文为[weixin_ fifty-one million one hundred and eighty-seven thousand]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207071136083598.html