【Leetcode】之Remove Duplicates from Sorted Array II

一.问题描述

Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?

For example,
Given sorted array nums = [1,1,1,2,2,3],

Your function should return length = 5, with the first five elements of nums being 1122 and 3. It doesn't matter what you leave beyond the new length.

二.我的解题思路

这道题首先需要理解题意,即需要以复制覆盖的方式来remove duplicate。我的思路是首先建立一个vector,然后遍历一次数组,记录下相邻元素不同的位置并且将这些位置存入vector中。比如对于[1,1,1,2,2,3],那么遍历完一次数组之后,vector中就存放着[-1,2,4,5]其中-1是人为加的,而2,4,5则代表着nums[2]!=nums[2+1]诸如此类。vector中的这些位置下标将数组nums分成了不同的段。

接下来就是遍历vector并进行移位覆盖,注意移动的位数是有叠加的。测试通过的程序如下:

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int len = nums.size();
        int res=0;
        if(len<=2) return len;
        int i=0;
        vector<int> record;record.push_back(-1);
        while(i+1<len){
            if(nums[i]!=nums[i+1])
                record.push_back(i);
            i++;
        }
        record.push_back(len-1);
        int rec_len = record.size(); int step=0;
        for(int i=1;i<rec_len;i++){
            int curr_step = (record[i]-record[i-1]<=2)?0:(record[i]-record[i-1]-2);
            step+=curr_step;
            if(curr_step==0) res+=record[i]-record[i-1]; else res+=2;
            int st_idx=record[i]+1;
            if(st_idx>=len) break;
            int cnt=0;
            while(st_idx<=record[i+1] && cnt<2){
                nums[st_idx-step]=nums[st_idx];
                cnt++;
                st_idx++;
                
            }
            
                
            
             
        }
        return res;
      
    }
};


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值