给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素最多出现两次,返回移除后数组的新长度。
不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array-ii
nums = [1,1,1,1,2,2,3,3,3]
i = 0 #慢指针
j = i + 1 #快指针
n = len(nums)
c = 1 #计数器
while i < len(nums) - 2 and nums[i] != None: # 为了防止出现下标越界
if j == len(nums): # 当快指针移动到列表外,慢指针移动1位,计数器归1
i += 1
c = 1
j = i + 1
continue
elif nums[i] == nums[j]:
c += 1
if c > 2:
nums[j:len(nums) -1] = nums[j+1:] # 第3个重复值之后的元素向前移动
j -= 1
n -= 1
c = 2
nums[-1] = None # 最后一个元素设置为空
j += 1 #快指针移动
print(nums,n)
数出结果为
[1, 1, 2, 2, 3, 3, None, None, None] 6