[LeetCode] Remove Duplicates from Sorted Array II

80.

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]);
}

题目要求数组中的重复数字不能超过2个,求出符合要求的数组长度。并且按照这个长度取出的数组要符合重复数字不超过2个的要求,因此要用后边的元素将多余的元素覆盖掉。

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if(nums.size()<2)return nums.size();
        int flag=0,cur=1,count=1;
        while(cur<nums.size()){
            if(nums[flag]==nums[cur] && count==0)++cur;
            else{
                if(nums[flag]==nums[cur])--count;
                else{
                    count=1;
                }
                nums[++flag]=nums[cur++];
            }
        }
        return flag+1;
    }
};

使用flag记录符合要求的数组当前位置,即flag以前(包括flag本身)的数组中重复元素不超过2个,定义名为cur的迭代器,当数组中cur所对应的值与flag对应的值不相同时,就从cur开始对数组进行覆盖。
为了使flag停在正确的位置,使用count来计数重复元素的个数。当count为0,即达到最大重复长度2时,只让cur向前探索直到找到异类。
只要cur和flag对应的元素不相等或者count不为0就执行 nums[++flag]=nums[cur++]; 保证了后边数组向前的覆盖。

参考:https://www.cnblogs.com/grandyang/p/4329295.html

猜你喜欢

转载自www.cnblogs.com/cff2121/p/10800209.html