LeetCode removes simple elements Java double pointer

Given an array of nums and a value of val, you need to remove all the elements whose value is equal to val in place, and return the new length of the removed array.

Don't use extra array space, you must use only O(1) extra space and modify the input array in-situ.

The order of the elements can be changed. You don't need to consider the elements in the array beyond the new length.Insert picture description here

Insert picture description here
Related topics move zero

Ideas

双指针,不让开辟新的空间只能在原数组上修改,
1.按照双指针的套路定义left和right,两个指针同时走遇
到目标值,此时left停下,right++,直nums[right]!=target;
2.此时nums[rigth]!=target,直接nums[left]=nums[right],left++,right++;

Insert picture description here
Code:

class Solution {
    
    
    public int removeElement(int[] nums, int val) {
    
    
        int length=nums.length;
        int l=0;
        int r=0;
        int ans=0;
        while(r<nums.length){
    
    
            if(nums[l]==val){
    
    
                r++;
            }
            else{
    
    
            nums[l]=nums[r];
            l++;
            r++;
            }
        }
        return l;
    }
}

Guess you like

Origin blog.csdn.net/qq_44844588/article/details/108139521