80. Remove Duplicates from Sorted Array II

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.

Example 2:

Given nums = [0,0,1,1,1,1,2,3,3],

Your function should return length = 7, with the first seven elements of nums being modified to 0, 0, 1, 1, 2, 3 and 3 respectively.

It doesn't matter what values are set beyond the returned length.

Clarification:

Confused why the returned value is an integer but your answer is an array?

Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.

Internally you can think of this:

// nums is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums);

// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
    print(nums[i]);
}
It has been declared "It doesn't matter what values are set beyond the returned length"
方法和26题一样,区别是多一个flag用来判断相同的数量是否小于3个。
class Solution {
    public int removeDuplicates(int[] nums) {
        if (nums.length <= 2) return nums.length;
        int i = 0;
        int flag = 1;
        for(int j = 1; j < nums.length; j++){
            if(nums[i] != nums[j]){
                i++;
                nums[i] = nums[j];
                flag = 1;
            }
            else{
                if(flag < 2){
                    flag++;
                    i++;
                    nums[i] = nums[j];
                }
            }
        }
        return i+1;
    }
}

方法二:将当前快指针遍历的数字和慢指针指向的数字的前一个数字比较(也就是满足条件的倒数第 2 个数),如果相等,因为有序,所有倒数第 1 个数字和倒数第 2 个数字都等于当前数字,

再添加就超过 2 个了,所以不添加,如果不相等,那么就添加。

public int removeDuplicates2(int[] nums) {
    int slow = 1;
    int fast = 2;for (; fast < nums.length; fast++) {
        //不相等的话就添加
        if (nums[fast] != nums[slow - 1]) {
            slow++;
            nums[slow] = nums[fast];
        }
    }
    return slow + 1;
}
public class Solution {
    public int removeDuplicates(int[] nums) {
        if (nums.length <= 2) return nums.length;

        int index = 2;
        for (int i = 2; i < nums.length; i++){
            if (nums[i] != nums[index - 2])
                nums[index++] = nums[i];
        }

        return index;
    }
};

 

https://soulmachine.gitbooks.io/algorithm-essentials/java/linear-list/array/remove-duplicates-from-sorted-array-ii.html
https://leetcode.wang/leetCode-80-Remove-Duplicates-from-Sorted-ArrayII.html
posted @ 2019-08-06 00:31  Schwifty  阅读(142)  评论(0编辑  收藏  举报