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].
Solution: add a boolean variable for indicating whether the duplicates appear twice.
The following code passes LeetCode OJ Large Judge.
class Solution {
public:
    int removeDuplicates(int A[], int n) {
        int i = 0;
        if(n == 0) return n;
        bool flag = true;
        for(int j = 1; j < n; j++) {
            if(flag) {
                if(A[i++] == A[j]) flag = false;
                A[i] = A[j];
            }
            else {
                if(A[i] != A[j]) {
                    A[++i] = A[j];
                    flag = true;
                }
            }
        }
        return i+1;
    }
};

Comments

Popular posts from this blog

Maximum Gap

[ITint5] Maximum Subarray for a Circular Array

[CC150] Chapter 4 Trees and Graphs