Leetcode double pointer delete duplicates in sorted array java

Title description
Given a sorted array, you need to delete the repeated elements in place, so that each element only appears once, and return the new length of the removed array.
Don't use extra array space, you must modify the input array in place and use O(1) extra space.
Example 1:
Given the array nums = [1,1,2], the
function should return the new length 2, and the first two elements of the original array nums are modified to 1, 2.
You don't need to consider the elements in the array beyond the new length.

len represents the length of the new array, define two pointers, i is in the front, the initial value is 0, which means the slow pointer, j is in the back, the initial value is 1, which means the fast pointer
If nums[j] = nums[i] then skip Loop, j is moved one bit backward.
If nums[j] != nums[i], then i is moved one bit backward, j is moved one bit backward, len is incremented by one, and the element at position j is copied to position i+1.
Repeat the above Process until j is equal to the length of the array.
Return len, which is the length of the new array.
Insert picture description here
Insert picture description here
Code:

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

Guess you like

Origin blog.csdn.net/stonney/article/details/112137547