Leetcode 80. 删除排序数组中的重复项 ii remove-duplicates-from-sorted-array-ii——去除重复

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

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

Your function should return length =5, and A is now[1,1,2,2,3].

这道题跟Remove Duplicates from Sorted Array比较类似,区别只是这里元素可以重复出现至多两次,而不是一次。其实也比较简单,只需要维护一个counter,当counter是2时,就直接跳过即可,否则说明元素出现次数没有超,继续放入结果数组,若遇到新元素则重置counter。总体算法只需要扫描一次数组,所以时间上是O(n),空间上只需要维护一个index和counter,所以是O(1)。

复制代码
 1 class Solution {
 2 public:
 3     int removeDuplicates(int A[], int n) {
 4         if(A==NULL||n<1) return 0;
 5         int count=0;
 6         int res=0;
 7         for(int i=0;i<n;i++){
 8             if(i>0&&A[i]==A[i-1]){
 9                 count++;
10             }else
11                 count=0;
12             if(count<2){
13                 A[res++]=A[i];
14             }
15         }
16         return res;
17     }
18 };
复制代码

 或者直接比较j-1和j-2

复制代码
class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int n=nums.size();
        int i=0,j=0;
        for(i=0;i<n;++i)
        {
            if(j>1&&nums[i]==nums[j-1]&&nums[i]==nums[j-2])
                continue;
            nums[j++]=nums[i];
        }
        return j;
    }
};
复制代码

 

posted @   鸭子船长  阅读(142)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示