```
public class Solution {
public int removeDuplicates(int[] nums) {
int n=nums.length;
if(n<=2) return n;
int i=1,j=1,count=1;
while(j<n){
if(nums[j]!=nums[j-1]){
nums[i++]=nums[j];
count=1;
}else{
if(count<2){
nums[i++]=nums[j];
count++;
}
}
j++;
}
return i;
}
}
```