嗯 这题没有想好,这个做法是看的网络上的,然后复现了一下
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
idx = 0
count = 0
for i in range(len(nums)):
if i != 0 and nums[i] == nums[i-1]:
count += 1
if count >= 3:
continue
else:
count = 1
nums[idx] = nums[i]
idx += 1
return idx
另一种做法是用一个指针J 来指向当前位置和下一个位置,判断是否相等,如果相等 两个数字都存下来,如果不同,存下来当前的数字,还要注意去重
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
if n == 0 or n == 1 or n == 2:
return n
i = 0
j = 0
while i < n and j < n:
if j + 1 < n and nums[j] == nums[j+1]:
nums[i] = nums[j]
nums[i+1] = nums[j+1]
i += 2
while j < n and nums[j] == nums[i - 1]:
j += 1
else:
nums[i] = nums[j]
i += 1
j += 1
return i