[LeetCode] Remove Duplicates from Sorted Array II [27]

题目

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次以上出现的数,可是能够同意反复2次。
这个题类似Remove Duplicates from Sorted Array,第一个想法非常直接就是计数,超过2次的就忽略,根据这个思路的代码见代码一;
上面的思路可行。可是代码看着比較冗余,推断比較多。再来想想原来的数组,该数组是排好序的。假设一个数出现3次以上,那么必有A[i] == A[i-2]。所以依据这个关系能够写出比較精简的代码二。

详见代码。


代码实现

代码一

class Solution {
public:
    int removeDuplicates(int A[], int n) {
        if(A==NULL || n<=0) return 0;
        int start=1, count = 1, back = A[0];
        for(int i=1; i<n; ++i){
            if(count<2){
                A[start++] = A[i];
                if(back != A[i]){
                    back = A[i];
                    count = 1;
                }else{
                    ++count;
                }
            }else{
                if(A[i] != back){
                    count = 1;
                    A[start++] = A[i];
                    back = A[i];
                }else{
                    ++count;
                }
            }
        }
        return start;
    }
};
代码二

class Solution {
public:
    int removeDuplicates(int A[], int n) {
        if(A==NULL || n<=0) return 0;
        if(n==1) return 1;
        int start=1,back = A[1];
        for(int i=2; i<n; ++i){
            if(A[i] != A[i-2]){
                A[start++] = back;
                back = A[i];
            }
        }
        A[start++] = back;
        return start;
    }
};

假设你认为本篇对你有收获,请帮顶。


另外。我开通了微信公众号--分享技术之美,我会不定期的分享一些我学习的东西.

你能够搜索公众号:swalge 或者扫描下方二维码关注我

(转载文章请注明出处: http://blog.csdn.net/swagle/article/details/29822565 )

原文地址:https://www.cnblogs.com/tlnshuju/p/6872783.html