[LintCode/LeetCode] Remove Duplicates from Sorted Array I & II

436 查看

Remove Duplicates from Sorted Array I

Problem

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.

Example

Given input array A = [1,1,2],

Your function should return length = 2, and A is now [1,2].

Note

思路:原数组长度为0,则返回0;原数组长度不为0,则至少有index = 1个元素。循环整个数组,比较nums[i]nums[i-1]。将所有不重复的数值赋给nums[index],而当nums[i]nums[i-1]相等时,不做处理。最后返回的index就是不同元素的个数,也是新数组的长度。

Solution

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

Remove Duplicates from Sorted Array II

Problem

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

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

Your function should return length = 5, and A is now [1,1,2,2,3].

Note

相同的思路,加入一个count变量,每次循环比较前后元素是否重复时,更新该元素出现的次数count。只有在count <= 2时,才对nums[index]赋值。
注意,每次初始化count的时候要分两种情况:i == 0 || nums[i] != nums[i-1],这就意味着从i = 0的时候开始遍历。

Solution

public class Solution {
    public int removeDuplicates(int[] nums) {
        if (nums.length == 0) return 0;
        int index = 0, count = 0;
        for (int i = 0; i < nums.length; i++) {
            if (i == 0 || nums[i] != nums[i-1]) count = 1;
            else count++;
            if (count <= 2) {
                nums[index] = nums[i];
                index++;
            }
        }
        return index;
    }
}