LeetCode | Remove Duplicates from Sorted Array II(删除重复的元素2)


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].


题目解析:

最多允许两个重复,输出结果数组。


方案一:

可以另外设置O(n)的辅助空间,对每一个数据进行计数,多于2个的只输出两个,少于两个的只输出1一个。

这个方法很容易想,但不是高效的算法。要去思考如何不使用辅助空间。


方案二:

Remove Duplicates from Sorted Array 类似,这里用个计数变量count,当超过两个的时候,就不再移动i指针。其中有一点小细节是:开始时i和j相等,是不需要进行交换的。但是为了代码简单,忽略这种情况。只要count<=2或者arr[j] != temp的时候,都进行交换。

class Solution {
public:
    int removeDuplicates(int A[], int n) {
        int i=0,j=0;
        int count = 0;
        int temp = A[0];
        while(j<n){
            if(A[j] == temp){   //如果和参考值相等
                if(count<=2){   //当个数少于两个的时候,就交换,无论i和j是否相等,减少分支条件
                    count++;
                    Swap(&A[i],&A[j]);
                    i++;
                }
                    count++;    //无论count是否小于2,都要进行计数
                    j++;        //都要让j++
                continue;
            }
            count = 1;          //当和参考值不相等的时候,count重新置一,并且更新参考值
            temp = A[j];
            Swap(&A[i],&A[j]);
            i++;
            j++;
        }
        return i;
    }
    void Swap(int *a,int *b){
        int tmp = *a;
        *a = *b;
        *b = tmp;
    }
};






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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值