80. Remove Duplicates from Sorted Array II
# Runtime: 52 ms, faster than 83.68%; Memory Usage: 14.1 MB, less than 99.96%
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
if not nums:
return 0
left, right = 0, 0 # 双指针,right代表当前遍历到的位置,left代表删除重复元素后当前的位置
count = 0 # 统计相同元素的个数,但最多只统计2个
tmp = nums[0] # 代表当前要统计的个数
while right < len(nums):
if nums[right] == tmp:
if count < 2:
count += 1
right += 1
else:
while count:
nums[left] = tmp
left += 1
count -= 1
tmp = nums[right]
while count:
nums[left] = tmp
left += 1
count -= 1
return left