题解1
思路
# 定义两个指针 p q 一个记录当前重复次数的变量 maxLen = 1 表示还可以重复几次
# 对数组进行遍历
# 如果nums[p] == nums[q] :
# if maxLen == 0:
# continue
# else:
# maxLen–
# 对p进行修改
# 否则
# 重置maxLen 为 1
# 对p进行修改
复杂度分析
空间复杂度 O(1)
时间复杂度 O(N)
代码
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
# 定义两个指针 p q 一个记录当前重复次数的变量 maxLen = 1 表示还可以重复几次
# 对数组进行遍历
# 如果nums[p] == nums[q] :
# if maxLen == 0:
# continue
# else:
# maxLen--
# 对p进行修改
# 否则
# 重置maxLen 为 1
# 对p进行修改
length = len(nums)
p = 0
q = 1
maxLen = 1
if length == 0 or length == 1:
return length
for q in range(1, length):
if nums[p] == nums[q]:
if maxLen == 0:
continue
else:
maxLen = maxLen - 1
p = p + 1
nums[p] = nums[q]
else:
maxLen = 1
p = p + 1
nums[p] = nums[q]
return p + 1