Notes:

For sorted array, there are two properties we can use:

1. All duplicates are stay togethers (First solution)

2. Ascending order (Second solution)

 

class Solution {
    public int removeDuplicates(int[] nums) {
        if (nums.length < 3) {
            return nums.length;
        }
        
        int start = 1;
        int prev = nums[0];
        boolean found = false;
        for (int i = 1; i < nums.length; i++) {
            if (prev == nums[i]) {
                if (found) {
                    continue;
                }
                found = true;
            } else {
                found = false;
            }
            nums[start++] = nums[i];
            prev = nums[i];
        }
        return start;
    }
}

 

 

class Solution {
    public int removeDuplicates(int[] nums) {
        if (nums.length < 3) {
            return nums.length;
        }
        
        int start = 0;
        for (int num : nums) {
            if (start < 2 || nums[start - 2] < num) {
                nums[start++] = num;
            }
        }
        return start;
    }
}

 

posted on 2017-09-03 16:37  keepshuatishuati  阅读(96)  评论(0编辑  收藏  举报