Java two pointer method, without ordering condition


  • 0
    X

    I didn't notice the array is ordered, the following algorithm is suitable for more general cases such as "xxxxyyyzzz..."

    public int removeDuplicates(int[] nums) {
        if(nums == null || nums.length == 0) return 0;
        int slow = 0, fast = 0;
        int len = 0;
        while(fast < nums.length) {
            // intialization for the next step
            fast++; len = 1;    
            // move fast pointer, stop when meet new number
            while(fast<nums.length && nums[fast] == nums[fast-1]) { fast++; len++;}           
            // reconstruct array with slow pointer
            for(int i=0; i<Math.min(len, 2); ++i) { nums[slow++] = nums[fast-1];}
        }
        return slow;
    }

  • 0
    D

    The array has to be sorted. It would not work for case [1,1,1,0,0,0,0,1,1]


  • 0
    X

    yes, you are right.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.