I didn't notice the array is ordered, the following algorithm is suitable for more general cases such as "xxxxyyyzzz..."

```
public int removeDuplicates(int[] nums) {
if(nums == null || nums.length == 0) return 0;
int slow = 0, fast = 0;
int len = 0;
while(fast < nums.length) {
// intialization for the next step
fast++; len = 1;
// move fast pointer, stop when meet new number
while(fast<nums.length && nums[fast] == nums[fast-1]) { fast++; len++;}
// reconstruct array with slow pointer
for(int i=0; i<Math.min(len, 2); ++i) { nums[slow++] = nums[fast-1];}
}
return slow;
}
```