class Solution {
public:
int removeDuplicates(int A[], int n) {
if (n <= 2)
return n;
int rear = 1;
for(int i = 2; i < n; i++){
if(!(A[i] == A[rear] && A[i] == A[rear 1])){
A[++rear] = A[i];
}
}
return rear+1;
}
};
C++ simple AC solution in 10 lines 21ms

public int removeDuplicatesTwice(int[] nums){
if (nums.length==0)
return 0;
int count=1;
boolean flag=false;
for (int i=1;i<nums.length;i++){
if (nums[i]==nums[i1]){
if (!flag){
nums[count++]=nums[i];
flag=true;
}
// else
//
}
else{
flag=false;
nums[count++]=nums[i];
}} return count; }
