80. Remove Duplicates from Sorted Array II
Practice Remove Duplicates from Sorted Array II for free on NudgeCode: Medium, Two Pointers pattern. Write it in Python or JavaScript, run the tests in your browser, and ask for a hint when you are stuck.
nums is sorted in non-decreasing order. Rewrite it in place so that every value appears at most twice, keeping the original order, and return k, the number of elements kept.
After your function returns, the first k elements of nums must be the kept values, still sorted. What is left after position k doesn't matter. Use O(1) extra memory: change nums itself rather than building a new array.
The test checks both k and the first k elements of nums, written as [k, nums[:k]].
Example
nums = [1,1,1,2,2,3] -> [5, [1,1,2,2,3]]
nums = [0,0,1,1,1,1,2,3,3] -> [7, [0,0,1,1,2,3,3]]
In the first case the third 1 is dropped; both 2s stay because two copies are allowed.
Constraints
- 1 <= nums.length <= 3 * 10^4
- -10^4 <= nums[i] <= 10^4
numsis sorted in non-decreasing order