使用for循环删除列表中部分值的时候,索引值仍然递增但列表中的元素变少,导致部分元素被跳过没有遍历。
Solution:使用while循环:
Given an integer array nums
sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same.
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
i = 1
while i<= len(nums)-1:
if nums[i] == nums[i-1]:
nums.pop(i)
else:
i += 1
k = len(nums)
return k
while循环可以控制索引是否递增或以某种条件递增。