Question

Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

Example 1:

Given 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 respectively.

It doesn't matter what you leave beyond the returned length.

Thinking:

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

二刷

二刷的时候还是花了一些时间认真看题目,这道题看来一刷的时候写的很顺利,现在完全没有任何印象,好在还是写出来了。

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