Thinking process

find the first different number

Original(messy) version
public class Solution {
    public int removeDuplicates(int[] nums) {
        if (nums == null || nums.length == 0) return 0;

        int left = 0;
        int right = 0;

        while (left <= right && right < nums.length - 1) {
            while (right < nums.length && nums[left] == nums[right]) {
                right++;
            }

            if (right < nums.length && left + 1 < nums.length) {
                nums[left + 1] = nums[right];
                left++;
            }
        }

        return left + 1;
    }
}
Neat version
public class Solution {
    public int removeDuplicates(int[] nums) {
        if (nums.length < 1) return nums.length;

        int left = 0;
        int right = 1;

        while (right < nums.length) {
            if (nums[right] == nums[left]) {
                right++;
            } else {
                left++;
                nums[left] = nums[right];
                right++;
            }
        }

        return left + 1;
    }
}

Follow up - What if duplicates are allowed at most twice ?

LC 80. Remove Duplicates from Sorted Array II

public class Solution {
    public int removeDuplicates(int[] nums) {
        if (nums.length <= 2) return nums.length;

        int left = 1;
        int right = 2;

        while (right < nums.length) {
            if (nums[left] == nums[right] && nums[left] == nums[left - 1]) {
                right++;
            } else {
                left++;
                nums[left] = nums[right];
                right++;
            }
        }

        return left + 1;
    }
}

results matching ""

    No results matching ""