80. Remove Duplicates from Sorted Array II

T: O(n)

S: O(1)

class Solution {
    public int removeDuplicates(int[] nums) {
        if (nums == null || nums.length <= 2) {
            return nums.length;
        }
        
        int c = 2;
        for (int i = 2; i < nums.length; i++) {
            if (nums[c - 2] != nums[i]) {
                nums[c] = nums[i];
                c++;
            }
        }
        return c;
    }
    
}

/*
num sort in asc
remove some duplicates in-place
appears at most twice

     c i
[1,1,1,2,2,3]

    => c[2-2] = c[0] != nums[i], do replace, c++
     c i   
[1,1,1,2,2,3]


       c i
[1,1,2,2,2,3]

   => c[3-2] = c[1] != nums[i], do replace, c++
       c i
[1,1,2,2,2,3]

   => c[4-2] = c[2] != nums[i], do replace, c++
           c i
[1,1,'2',2,2,3]

=>
           c => c = 5
[1,1,2,2,3,3]

ans is [1,1,2,2,3]
*/

Last updated