https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array-ii/
# -*- coding:utf-8 -*- class Solution(object): def removeDuplicates(self, nums: list): """ :type nums: List[int] :rtype: int """ if len(nums) == 0: return 0 flag_nub = nums[0] flag_times = 0 current_idx = 0 while len(nums) > 0: if current_idx == len(nums): return len(nums) if flag_nub == nums[current_idx] and flag_times < 2: flag_times += 1 elif flag_nub == nums[current_idx]: nums.remove(nums[current_idx]) current_idx -= 1 else: flag_times = 1 flag_nub = nums[current_idx] current_idx += 1 return len(nums) if __name__ == '__main__': nums = [1, 1, 1, 2, 2, 3] nums = [0, 0, 1, 1, 1, 1, 2, 3, 3] print(Solution().removeDuplicates(nums))
思路:这道题其实思路不难,无非是遍历一下,然后用一个变量标记重复出现2次以上的元素进行删除。
但是有一个问题是python for的迭代器机制(之前已经提过),导致如果在for循环中对列表进行增删操作会导致异常,因此这里需要再引入一个变量使用while循环。
0 条评论