Remove Duplicates from Sorted Array in Java

Say you have an array of primitive integers and you want to remove all duplicates.

You can find out how many non-duplicate integers are in the array with this method:

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

Because we pass the nums array in as a reference, and modify the variable in-place with no additional space, you could just continue using it as is.

Your other option could be to return the nums variable at the end if you wanted the actual duplicates removed out:

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

Leave a Reply

Your email address will not be published.