public int removeDuplicates(int[] A) {
        int count = 1;
        int countAll = 0;
        int pre = Integer.MIN_VALUE;
        int removed = 0;
        HashSet<Integer> set = new HashSet<Integer>();
        for (int i = 0; i < A.length; i++) {
            int a = A[i];
            if (a == pre) {
                count++;
            } else {
                count = 1;
            }
            pre = a;
            if (count <= 2) {
                countAll++;
            } else {
                set.add(i);
                removed++;
            }
        }
        int index = 0;
        int[] B = new int[A.length - removed];
        for (int i = 0; i < A.length; i++) {
            if (!set.contains(i)) {
                B[index++] = A[i];
            }
        }

        for (int i = 0; i < B.length; i++) {
            A[i] = B[i];
        }
        return countAll;
    }