```
class Solution {
public:
int removeDuplicates(int A[], int n) {
int count = 0;
int i = 0;
int cmp;
if (n <= 1){
return n;
}
while (i < n - 1) {
if (A[i] != A[i + 1]){
A[count++] = A[i++]; // save the non-duplicates
}
else {
cmp = A[i];
A[count++] = A[i++]; // only save two duplicates
A[count++] = A[i++];
while (A[i] == cmp){ // skip the rest of the duplicates
i++;
}
}
}
if (count > 0 && i < n && A[i] != A[count - 1]) { // deal with the last element
A[count++] = A[i];
}
return count;
}
};
```