Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
Example 1:
Given nums = [1,1,1,2,2,3], Your function should return length = 5, with the first five elements of numsbeing 1, 1, 2, 2
and 3 respectively.
Example 2:
Given nums = [0,0,1,1,1,1,2,3,3], Your function should return length = 7, with the first seven elements of numsbeing modified to 0, 0, 1, 1, 2, 3 and 3 respectively.
列表已经从小到大排序完了,删除数字重复出现次数大于2次的,需要原地操作。
所以只需要记录当前数字出现次数即可。dup表示当前数字出现的次数。
如果dup>2则删除当前数字,注意此时nums的长度,记录位置的n,重复次数dup都需要-1。
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
length=len(nums)
n=1
dup=1
while n<length:
if nums[n]==nums[n-1]:
dup+=1
if dup>2:
nums.remove(nums[n])
dup-=1
length-=1
n-=1
else:
dup=1
n+=1

本文介绍了一种在不使用额外空间的情况下,修改输入数组以确保每个元素最多只出现两次的算法。通过记录当前元素的出现次数,当次数超过两次时,从数组中移除该元素,同时更新数组长度和计数器。此方法适用于已排序的数组。
1526

被折叠的 条评论
为什么被折叠?



