[leetcode-80-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 1, 1, 2, 2 and 3.
It doesn't matter what you leave beyond the new length.

思路:

声明两个指针first和second,first代表新的数组中最后一个元素的下一个位置,用来表示插入新元素的位置。

second表示当前遍历的元素位置,用来跟前一个元素比较是否相同,然后还需要一个计数器count,来统计相同元素出现的个数。

如果元素出现相同,然后观察此时count大小,如果之前只出现1次,则按正常处理(将当前遍历的元素插入到新位置,由first指出),然后count+1;

如果元素不相同,则置count为1.first与second同时移动。

int removeDuplicates(vector<int>& nums)
    {
        if (nums.size() <= 2)return nums.size();
        int first = 1;
        int second = 1;
        int count = 1;
        while (second<nums.size())
        {
            if (nums[second-1] == nums[second] )
            {
                if (count<2)
                {
                    nums[first++] = nums[second];
                    count++;
                }
            }
            else
            {
                count = 1;
                nums[first++] = nums[second];
            }
            second++;
        }
    }

另外对于更一般情况,允许元素重复次数为k次的,有大神提供了通用的思路

学习一下。

I think both Remove Duplicates from Sorted Array I and II could be solved in a consistent and more general way by 
allowing the duplicates to appear k times (k = 1 for problem I and k = 2 for problem II). Here is my way: we need
a count variable to keep how many times the duplicated element appears, if we encounter a different element, just
set counter to 1, if we encounter a duplicated one, we need to check this count, if it is already k, then we need
to skip it, otherwise, we can keep this element. The following is the implementation and can pass both OJ:
int removeDuplicates(int A[], int n, int k) { if (n <= k) return n; int i = 1, j = 1; int cnt = 1; while (j < n) { if (A[j] != A[j-1]) { cnt = 1; A[i++] = A[j]; } else { if (cnt < k) { A[i++] = A[j]; cnt++; } } ++j; } return i; } For more details, you can also see this post: LeetCode Remove Duplicates from Sorted Array I and II: O(N) Time and O(1) Space

参考:

https://discuss.leetcode.com/topic/7673/share-my-o-n-time-and-o-1-solution-when-duplicates-are-allowed-at-most-k-times

转载于:https://www.cnblogs.com/hellowooorld/p/6680007.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值