Fork me on GitHub

[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

posted @ 2017-04-07 21:11  hellowOOOrld  阅读(867)  评论(0编辑  收藏  举报