Simple Java AC Solution with Explanation

  • 0

    Picker works as an index. Since the array is sorted, each time a number first appears, we pick it. And then the same value may appear multiple times, while we just ignore them.

    Later on, if we come across a new number with a different value(a larger value actually, in this case), just add the index Picker by one to put the new value there.

    Finally, we return picker + 1 and for the border case (array nums has a length of zero) we return zero.

    Some might be confused with the return value length or duplicates by pointing out that "Your solution never removed the duplicates for some test cases". Well, what the problem requires is to do the work in-place, and by returning the new length, those duplicates with indexes after the new length are simply ignored. There is no "remove".

    public int removeDuplicates(int[] nums) {
        int picker = 0;
        for (int i = 1; i < nums.length; i++) if (nums[i] != nums[picker]) nums[++picker] = nums[i];
        return nums.length == 0 ? 0 : picker + 1;

Log in to reply

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