```
public class RemoveDuplicatesTwo {
public int removeDuplicates(int[] nums) {
/**
* Corner cases. If no data, then return 0
*/
if(nums == null || nums.length == 0) {
return 0;
}
int insertPos = 1;
boolean hasSeenTwo = false;
/**
* Algorithm is as follows:
* For every incoming integer from 1 to size-1, ask a question.
* - Is this new integer the same as last saved value?
* Yes -> a) Are there already two occurrences of this integer?
* No -> 1) Insert this new value into the position.
* Yes -> 2) There are already two of this value
* saved, so just continue.
* No -> b) This new number is never seen. We add it.
*
*/
for(int i = 1; i < nums.length; i++) {
if(nums[i] == nums[insertPos-1]) {
if(!hasSeenTwo) {
swap(nums, i, insertPos);
hasSeenTwo = true;
insertPos++;
} else {
continue;
}
} else {
hasSeenTwo = false;
swap(nums, i, insertPos);
insertPos++;
}
}
return insertPos;
}
private void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
```