LeetCode-80. Remove Duplicates from Sorted Array II

Description

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.

Solution 1(C++)

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int i = 0;
        for (int n : nums)
            if (i < 2 || n > nums[i-2])
                nums[i++] = n;
        return i;
    }
};

Solution 2(C++)

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        if (nums.empty()){
            return 0;
        }
        int n = nums.size();
        int times = 1;
        int cnt = 0;
        for (int i=1;i<nums.size();i++){
            if (nums[i] == nums[i-1]) times++;
            else times = 1;
            if (times > 2){
                nums.erase(nums.begin()+i);
                i--;
                cnt++;
            }
        }
        return n-cnt;
    }
};

Solution 3(C++)

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

算法分析

先说解法二,解法二应该是比较直观的算法,对于这种题我总是卡在如何删除vector中的某一个元素。可以使用函数v.erase()帮助完成。注意解法二中,cnt是删除掉元素的个数,然后for循环中,要不断判断与nums.size()的情况,注意nums.size()是会在erase()之后变化的。

关于解法一就比较有意思了。首先利用以及排好序的特点,如果一个nums[i] > nums[i-2]就说明,有超过2个重复的值出现。

解法二与解法三本质思想相同,但是解法三更加直观。解法三的思路是维护一个count与index。count是统计重复元素出现的次数,如果count > 2那么就跳过。如果< =2,那么就将nums[i]赋值给nums[index],其实如果这里将index换成新的结果数组,含义会更加直观。

还是不是很明白,以后要慢慢体会。

程序分析

关于v.erase()参考:C++——std::Vector

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值