Remove Duplicates from a Sorted List
You are given a list of integers sorted in non-decreasing order. Create a new list containing the required occurrences of each distinct value while preserving their original order.
The first method retains each distinct value once. The second method applies the same frequency limit to every distinct value. If a value occurs fewer times than the specified frequency, retain all its occurrences.
Method Signatures
Remove All Duplicate Copies
List<Integer> removeDuplicates(List<Integer> nums)
Return a new list containing exactly one occurrence of every distinct value.
Retain Duplicates with a Common Frequency Limit
List<Integer> retainDuplicates(List<Integer> nums, int frequency)
Return a new list containing at most frequency occurrences of every distinct value.
Parameters
nums is a list of integers sorted in non-decreasing order.
frequency is the maximum number of occurrences of each distinct value that retainDuplicates may include.
Return Value
Each method returns a new list containing the retained elements in sorted order. The original list must remain unchanged.
Constraints
1 <= nums.size() <= 30,000
-100 <= nums.get(i) <= 100
0 <= i < nums.size()
nums is sorted in non-decreasing order.
- For
retainDuplicates, 1 <= frequency <= nums.size().
Examples
Example 1
removeDuplicates(nums = List.of(1, 1, 1, 3, 3, 6, 8, 8))
Output: List.of(1, 3, 6, 8)
One occurrence of each distinct value is included in the new list.
Example 2
retainDuplicates(nums = List.of(-4, -4, -4, -1, -1, 2, 2, 2, 2, 7), frequency = 2)
Output: List.of(-4, -4, -1, -1, 2, 2, 7)
Every distinct value is included at most twice.
Example 3
retainDuplicates(nums = List.of(0, 0, 1, 1, 1, 1, 5, 5), frequency = 3)
Output: List.of(0, 0, 1, 1, 1, 5, 5)
The values 0 and 5 keep their two available occurrences, while 1 is limited to three occurrences.