Problem
The integer array nums is sorted in nondecreasing order. Modify it in place to retain at most two occurrences of each value, preserving their relative order. Return the retained length k; the first k positions must contain the resulting sorted sequence. Positions beyond that prefix are ignored.
Use constant extra memory and do not allocate a second array for the result. Preserve the original interface:
int removeDuplicates(vector<int>& nums);
Return only k; the prefix is an observable mutation of the argument, not an additional returned array.
Examples
Input: nums = [-3,-3,-3,0,0,0,4]
Returned k: 5
Required prefix: [-3,-3,0,0,4]
Input: nums = [6,6,6,6]
Returned k: 2
Required prefix: [6,6]
Constraints
-
1 <= nums.length <= 30000
.
-
Each value is between -10000 and 10000, inclusive.
-
Input order is nondecreasing; retain the original relative order.
-
Mutate the prefix using
O(1)
extra memory. The ignored suffix needs no special marker.