码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Remove Duplicates from Sorted Array II

时间:2019-05-01 18:34:11      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:执行   inpu   计数   lag   think   ica   appear   要求   cto   

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

[LeetCode] Remove Duplicates from Sorted Array II

标签:执行   inpu   计数   lag   think   ica   appear   要求   cto   

原文地址:https://www.cnblogs.com/cff2121/p/10800209.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!