[LeetCode] 80. 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 1122 and 3. It doesn't matter what you leave beyond the new length.

Thought process:
We can still use two pointers. The slow pointer points to current element in the new array, and the fast pointer points to the current element in the old array. Only write to new array if nums[fast] > nums[slow - 2].

Solution:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
    public int removeDuplicates(int[] nums) {
        int i = 0;
        for (int num : nums) {
            if (i < 2 || num > nums[i - 2]) {
                nums[i] = num;
                i++;
            }
        }
        return i;
    }
}

Time complexity: O(n). Space complexity: O(1).

Comments

Popular posts from this blog

[LeetCode] 269. Alien Dictionary

[LeetCode] 631. Design Excel Sum Formula

[LeetCode] 714. Best Time to Buy and Sell Stock with Transaction Fee