Example 1
- Input
- nums = [1,1,2]
- Output
- 2, nums = [1,2,_]
Two unique values exist, so k = 2 with nums[0] = 1 and nums[1] = 2; the entry after them is irrelevant.
Given an integer array nums sorted in non-decreasing order, remove the duplicates in place so that each unique value appears once at the front of the array while keeping their relative order. Return k, the number of unique elements.
Given an integer array nums sorted in non-decreasing order, remove the duplicates in place so that each unique element appears only once at the front of the array, keeping the relative order of the elements.
Return k, the number of unique elements. The first k entries of nums must hold those unique elements; the contents beyond index k - 1 do not matter.
1 <= nums.length <= 3 * 10^4-100 <= nums[i] <= 100nums is sorted in non-decreasing order.Two unique values exist, so k = 2 with nums[0] = 1 and nums[1] = 2; the entry after them is irrelevant.
Five unique values exist, so k = 5 with the front of the array reading 0, 1, 2, 3, 4.
The only value is already unique. The read/write loop does no work and returns k = 1.
Three copies of -1 and two copies of 0 collapse to two distinct values. Only the prefix [-1, 0] is checked; the remaining three slots may hold any values.
Sorted order makes repeated values consecutive. Keep the first value, then copy only the first value of each later run into the next open position. In [1, 1, 2], keep the first 1, skip the second 1, and write 2 into index 1. A read pointer visits the input while a write pointer counts the compacted prefix; the unused tail has no required contents.
Reveal Using a Set: intuition, complexity, and code
1 with left counting unique values.[1, 1, 1, 1], where the answer is 1 and only the front slot matters.[1, 2, 3, 4], where every value is written back onto itself and k = 4.[7], where the loop never runs and the answer is 1.nums[right] against nums[left], the write slot, instead of nums[right - 1], the previous read value.0, which treats the first element as its own duplicate and drops it.On sorted input, a reader pointer plus a writer pointer compacts matching runs in one pass with constant extra space.