题解 | #删除升序数组的重复元素(二)#
删除升序数组的重复元素(二)
https://www.nowcoder.com/practice/5b617a77d7654dc193bfe5c2bdaf5cc8
python 语言用for循环边遍历边删除,用逆序或者切片的方式,可以通过小数据量的用例,有一个十万个元素的用例运行超时了。
class Solution: def removenums(self , nums: List[int]) -> int: n = len(nums) cur = nums[-1] count = 1 for i in range(n-2,-1,-1): if nums[i] == cur: count += 1 if count >= 3: nums.remove(nums[i]) else: cur = nums[i] count = 1 return len(nums)
class Solution: def removenums(self , nums: List[int]) -> int: cur = nums[0] count = 1 for i in nums[1:]: if i == cur: count += 1 if count >= 3: nums.remove(i) else: cur = i count = 1 return len(nums)