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

Similar to Remove Duplicates From Sorted Array I,

If the current element is the same as previous element, if the count is less than 2 move the current element to the last tracked position, if the current element is different than previous element, also move the current element to the last tracked position.

public int removeDuplicates(int[] A) {
        if (A==null||A.length==0) {
            return 0;
        }

        int index=1;
        int count=1;

        for (int i=1; i<A.length; i++) {
            if (A[i]==A[i-1]) {
                if (count<2) {
                    A[index] = A[i];
                    index = index+1;
                } 
                count = count+1;
            } else {
                A[index] = A[i];
                index = index+1;
                count = 1;
            }       
        }
        return index;
    }