Remove Duplicates from Sorted Array

Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

For example, Given input array nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length.

解法:两个指针i,j。i循环移动,j指向最近的不重复元素,如果nums[i]和nums[j]不重复则将j+1位置的元素和i位置元素交换。

注意陷阱是最后需要返回的是数组长度,不是last index,所以需要加一。

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

Remove Duplicates from Sorted Array II

Follow up for "Remove Duplicates": What if duplicates are allowed at most twice?

For example, Given sorted array nums = [1,1,1,2,2,3],

Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn't matter what you leave beyond the new length.

接上题,这次允许每个元素重现一次重复。

解法上多一个计数器计算重复次数即可。

public int removeDuplicates(int[] nums) {
    if (nums.length == 0) {
        return 0;
    }
    int j = 0;
    int count = 0;
    for (int i = 1; i < nums.length; i++) {
        if (nums[i] == nums[i-1]) {
            count++;
            if (count < 2) {
                nums[++j] = nums[i];
            }
        } else {
            nums[++j] = nums[i];
            count = 0;
        }
    }
    return j+1;
}