dsa · medium
Remove Duplicates from Sorted Array II
nums is sorted non-decreasing. Remove extra duplicates in place so each distinct value appears at most twice. Relative order of the kept values must stay the same.
Arguments
nums— sorted non-decreasing array to compact in place
Return k, the number of kept values. The first k slots of nums must hold that result; anything past index k is ignored. The judge checks the returned k (which is determined by the at-most-two rule).
Example
[1,1,1,2,2,3]: keep two 1s, two 2s, and the 3. Return 5; the first five slots are 1,1,2,2,3.
[0,0,1,1,1,1,2,3,3]: keep two 0s, two 1s, one 2, two 3s → k = 7.
[1] → 1.
Constraints
1 <= nums.length <= 4*10^4 -10^4 <= nums[i] <= 10^4 nums is sorted non-decreasing Hidden tests include near-max size for this bound; a slower-than-intended solution TLEs.
Examples
Example 1
Input: [1,1,1,2,2,3] Expected: 5
Example 2
Input: [0,0,1,1,1,1,2,3,3] Expected: 7
Example 3
Input: [1] Expected: 1