80. Remove Duplicates from Sorted Array II
Given an integer array nums sorted in non-decreasing order, remove some duplicates in-place such that each unique element appears at most twice. The relative order of the elements should be kept the same
Example 1:
- Input:
nums = [1,1,1,2,2,3] - Output:
5, nums = [1,1,2,2,3,_] - Explanation: Your function should return
k = 5, with the first five elements ofnumsbeing1,1,2,2and3respectively. It does not matter what you leave beyond the returnedk(hence they are underscores).
Example 2:
- Input:
nums = [0,0,1,1,1,1,2,3,3] - Output:
7, nums = [0,0,1,1,2,3,3,_,_] - Explanation: Your function should return
k = 7, with the first seven elements ofnumsbeing0,0,1,1,2,3and3respectively. It does not matter what you leave beyond the returnedk(hence they are underscores).
Constraints:
1 <= nums.length <= 3 * 10^4-10^4 <= nums[i] <= 10^4numsis sorted in non-decreasing order.
Solution
class Solution:
def removeDuplicates(self, nums: list[int]) -> int:
slow = 0
for fast in range(len(nums)):
if slow < 2 or nums[fast] != nums[slow - 2]:
nums[slow] = nums[fast]
slow += 1
return slow