Remove Duplicates from Sorted Array II

Follow up for “Remove Duplicates”:
What if duplicates are allowed at most twice?

For example,
Given sorted array nums = [1,1,1,2,2,3],

Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn’t matter what you leave beyond the new length.

Solution:

  1. public class Solution {
  2. public int removeDuplicates(int[] nums) {
  3. if (nums == null) return 0;
  4. if (nums.length < 3) return nums.length;
  5. int n = nums.length;
  6. int i = 2;
  7. for (int j = 2; j < n; j++) {
  8. if (nums[j] != nums[i - 2]) {
  9. nums[i++] = nums[j];
  10. }
  11. }
  12. return i;
  13. }
  14. }