1. 程式人生 > >[LeetCode] Remove Duplicates from Sorted Array II 有序陣列中去除重複項之二

[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].

這道題是之前那道 Remove Duplicates from Sorted Array 有序陣列中去除重複項 的延續,這裡允許最多重複的次數是兩次,那麼我們就需要用一個變數count來記錄還允許有幾次重複,count初始化為1,如果出現過一次重複,則count遞減1,那麼下次再出現重複,快指標直接前進一步,如果這時候不是重複的,則count恢復1,由於整個陣列是有序的,所以一旦出現不重複的數,則一定比這個數大,此數之後不會再有重複項。理清了上面的思路,則程式碼很好寫了:

class Solution {
public:
    int removeDuplicates(int A[], int n) {
        if (n <= 2) return n;
        int pre = 0, cur = 1, count = 1;
        while (cur < n) {
            if (A[pre] == A[cur] && count == 0) ++cur;
            else {
                if (A[pre] == A[cur]) --count;
                
else count = 1; A[++pre] = A[cur++]; } } return pre + 1; } };