/***
 * 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].
 */
public class Solution {
    public int removeDuplicates(int[] A) {
        if (A.length == 0)
            return 0;
        int index = 0;
        int counter = 1;
        for (int i = 1; i < A.length; i++) {
            if (A[i] != A[index]) {
                index++;
                A[index] = A[i];
                counter = 1;
            } else if (counter == 1) {
                index++;
                A[index] = A[i];
                counter++;
            } else 
                counter = 0;
        }
        return index + 1;
    }
}

@@ -245,16 +245,57 @@
 ution %7B%0A
+    // Solution 1: T O(n), S O(1)%0A    /*%0A
     publ
@@ -809,10 +809,765 @@
 ;%0A    %7D%0A
+    */%0A    // Solution 2:  T O(n), S O(1)%0A    public int removeDuplicates(int%5B%5D A) %7B%0A        // Good scalability, change 2 to 3, then can handle at most three times%0A        if (A.length %3C= 2)%0A            return A.length;%0A        int index = 2;%0A        for (int i = 2; i %3C A.length; i++) %7B%0A            if (A%5Bi%5D != A%5Bindex - 2%5D)%0A                A%5Bindex++%5D = A%5Bi%5D;%0A        %7D%0A        return index;%0A    %7D%0A    %0A    // Solution 3: T O(n), S O(1)%0A    /*%0A    public int removeDuplicates(int%5B%5D A) %7B%0A        int index = 0;%0A        int n = A.length;%0A        for (int i = 0; i %3C n; i++) %7B%0A            if (i %3E 0 && i %3C n - 1 && A%5Bi%5D == A%5Bi - 1%5D && A%5Bi%5D == A%5Bi + 1%5D)%0A                continue;%0A            A%5Bindex++%5D = A%5Bi%5D;%0A        %7D%0A        return index;%0A    %7D%0A    */%0A%0A
 %7D%0A

add RemoveDuplicatesfromSortedArrayII.java