zoukankan      html  css  js  c++  java
  • [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

  • 相关阅读:
    对学生排序 Exercise07_17
    消除重复 Exercise07_15
    计算gcd Exercise07_14
    随机数选择器 Exercise07_13
    dom4j 学习总结
    jQuery学习总结(二)
    jQuery学习总结(一)
    SQL中Where与Having的区别
    html + css (1)
    struts2+json
  • 原文地址:https://www.cnblogs.com/hellowooorld/p/6680007.html
Copyright © 2011-2022 走看看