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.Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array
nums
. More formally, if there arek
elements after removing the duplicates, then the firstk
elements ofnums
should hold the final result. It does not matter what you leave beyond the firstk
elements.Return
k
after placing the final result in the firstk
slots ofnums
.Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.
class Solution:
def removeDuplicates(self, nums):
# length < 3 则不存在多余的数
if len(nums) < 3:
return len(nums)
# i: 指向需要被替换的位置
# j: 检测每一个数是否为多余的
i, j = 2, 2
while j < len(nums):
if nums[j] > nums[i - 2]:
nums[i] = nums[j]
i += 1
j += 1
return i