How to use double pointers gracefully---giving you an array of nums and a value of val, you need to remove all elements whose value is equal to val in place, and return the new length of the removed array.

Topic: 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 only use 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.

Solution 1: Traverse the array so that the elements in the array equal to this value are overwritten until the array is traversed.

class Solution {
    
    
    public int removeElement(int[] nums, int val) {
    
    
       int i=0;
       for(int j=0;j<nums.length;j++){
    
    
           if(nums[j]!=val){
    
    
               nums[i]=nums[j];
               i++;
           }
       }
       return i;
    }
    
}

Idea 2:
This method is of course able to traverse the array as little as possible, so that the two pointers point to the beginning and the end of the array respectively. The previous pointer is traversed backward, and if an element equal to val is encountered, it is exchanged with the following array
. Until the two pointers meet.

class Solution {
    
    
    public int removeElement(int[] nums, int val) {
    
    
       int i=0;
       int j=nums.length;
       while(i<j){
    
    
           if(nums[i]==val){
    
    
               nums[i]=nums[j-1];
               j--;
           }else{
    
    
               i++;
           }
       }
       return j;
    }
    
}

Guess you like

Origin blog.csdn.net/weixin_43815275/article/details/113098668