Algorithm training|Remove elements

Insert picture description here
Insert picture description here
Insert picture description here
Idea: To use dual pointers, first let the two pointers move synchronously. When val!=nums[fastindex], slowindex and fastindex move synchronously, so that the effect of "deleting elements" can be simulated later, because when val!=nums[fastindex] When val==nums[fastindex], fastindex is moved, but slowindex is not. The elements between the two will be "deleted" by moving synchronously when val!=nums[fastindex].

class Solution {
    
    
    public int removeElement(int[] nums, int val) {
    
    
        int slowIndex = 0; 
        for (int fastIndex = 0; fastIndex < nums.length; fastIndex++) {
    
      
            if (val != nums[fastIndex]) {
    
     
                //当val!=nums[fastIndex]的时候,slowIndex和fastIndex是同步移动的
                nums[slowIndex++] = nums[fastIndex]; 
            }
            //当val==nums[fastIndex]的时候,fastIndex移动,但是slowIndex不移动
        }
        return slowIndex;
    }
}

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_45394002/article/details/115315524
Recommended