26. Remove Duplicates from Sorted Array

# Easy

Solution:

  1. consider edge cases: 0 or 1 element

  2. use a pointer to track and store current non-repeated element

  3. return length = p+1

// Java
    public int removeDuplicates(int[] nums) {
        if(nums.length <= 1)
            return nums.length;
            
        int p1 = 0;
        for(int p2 = 1; p2 < nums.length; p2 ++) {
            if(nums[p2] != nums[p1]) {
                p1 ++;
                nums[p1] = nums[p2];
            }
        }
        
        return p1+1;
    }
}

Last updated