Remove Duplicates from Sorted Array II
Given an integer array nums sorted in non-decreasing order, remove some duplicates in-place so that each unique element appears at most twice. The relative order must be kept. Return k, the number of retained elements; the first k slots of nums must hold the final result, and what remains beyond k does not matter.
Open official problem prompt ↗Compact a sorted array so that no value appears more than twice, reporting how many elements remain.
Restocking a shelf where the policy allows at most two of any item facing forward: as you slide items left to fill gaps, you refuse to place a third identical can next to the two already there.
- Input
- nums = [1, 1, 1, 2, 2, 3]
- Output
- 5, with nums starting [1, 1, 2, 2, 3, _]
- Why
- The third 1 is dropped; every value now appears at most twice, leaving 5 elements.
1 <= nums.length <= 3 * 10^4-10^4 <= nums[i] <= 10^4nums is sorted in non-decreasing order