Double pointer method to solve the problem of deleting duplicate elements in an array

  Problem description: Given a sorted array, it is required to remove duplicate elements in place so that each element occurs only once, and return the new length of the removed array. And don't use extra array space.



  Algorithm ideas:
 ①Define fast as 1 and slow as 0, where fast and slow represent the subscripts of the array
 ②If the contents of fast and slow are equal, let fast take a step backward, and then judge, if it is always equal, fast will always be Go backward until the contents of slow and fast are not equal. When the contents of slow and fast are not equal, those elements between slow and fast are actually not repeated, so let slow take one step back at this time, and then set the value of fast. Assign it to slow, fast++ judges the next element
 ③ When the whole loop is over, return the number of elements in the array at this time, let slow+1 be the current length of the array after removing the duplicate elements



As shown in the figure :
insert image description here

Reference Code:

public class Test {
    
    
    public static void main(String[] args) {
    
    
        int[] arr={
    
    1,2,2,3,3,4,5,5};
        int i=remove(arr);
        System.out.println(i);
    }


    public static  int remove(int[] arr){
    
    
        if(arr.length<0){
    
    
            return 0;
        }
        int fast=1;      //初始fast为1号下标
        int slow=0;      //初始slow为0号下标
        while(fast<arr.length){
    
    
            if(arr[slow]==arr[fast]){
    
    
                fast++;
            }else{
    
    
                slow++;                  //此时不相等,所以fast的值要放在slow的下一个位置。即让slow先走一步再赋值,
                arr[slow]=arr[fast];    //赋值
                fast++;
            }
        }
        return slow+1;
    }
}


//
5

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324137805&siteId=291194637