Remove Duplicates from Sorted Array II

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

  • Time: O(n)
  • Space: O(1)
public int removeDuplicates(int[] nums) {
    if (nums.length <= 2) return nums.length;
    int count = 2;
    for (int i = count; i < nums.length; i++) {
        if (nums[i] != nums[count - 2]) {
            nums[count++] = nums[i];
        }
    }
    return count;
}

results matching ""

    No results matching ""