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 A = [1,1,1,2,2,3],

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

                   在元素递增的数组中,删除必要元素,使得单个元素的重复次数<=2。


        首先可以想到的是用双指针,然后对元素重复次数计数,可以在O(N)时间内完成处理。

class Solution {
public:
    int removeDuplicates(int A[], int n) {
        if(A==NULL || n<=0)
			return 0;
		int slow = 0, fast = 0;
		int times = 1;
		while(++fast<n){
			if(A[fast]==A[fast-1]){
				if(++times<=2)//判断重复次数是否小于等于2
					A[++slow] = A[fast];
			}else{
				times = 1;//遇到新元素则计数置一
				A[++slow] = A[fast];
			}
		}
		return slow+1;
    }
};

        这里还有更精简伶俐的写法:判断当前快指针所指元素是否与慢指针之前的那个元素相同,如果不相同那么重复次数一定小于3,即可满足条件。

class Solution {
public:
    int removeDuplicates(int A[], int n) {
        if(A==NULL || n<=2)
			return n;
		int slow = 1, fast = 1;
		while(++fast<n){
			if(A[fast]!=A[slow-1])
				A[++slow] = A[fast];
		}
		return slow+1;
    }
};



参考:https://oj.leetcode.com/discuss/2754/is-it-possible-to-solve-this-question-in-place

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值