80. Remove Duplicates from Sorted Array II — Python beats 98.40% using collections.Counter!
Python's collections.Counter() counts elements in a list and returns a dictionary.
For example, nums = [1, 1, 1, 2, 2, 3] → Counter({1: 3, 2: 2, 3: 1}).
- Traverse the dictionary: when
value > 2, setvalue = 2. This caps any element appearing more than twice down to 2. - Convert
Counter({1: 2, 2: 2, 3: 1})back to a list usingelements().
Since the problem passes nums by reference, we just need to clear nums and extend it with the modified list.
from collections import Counter # import
class Solution:
def removeDuplicates(self, nums: List[int]) -> List[int]:
dict1 = Counter(nums)
for i in dict1:
if dict1[i] > 2:
dict1[i] = 2
list1 = list(dict1.elements())
nums.clear() # clear the list
nums.extend(list1) # add elements back
return len(nums)Complexity Analysis
Time complexity: O(n), where n is the length of the array. We traverse the array at most once.
Space complexity: O(1). We only use constant space for a few variables.
贡献者
最近更新
Involution Hell© 2026 byCommunityunderCC BY-NC-SA 4.0
Python beat98.40% collectionsofCounter method!
LeetCode 80. 删除有序数组中的重复项 II 题解 — 使用双指针原地修改数组,允许每个元素最多出现两次,关键技巧是维护慢指针控制写入位置与快指针遍历数组,适合准备面试、需要掌握数组去重与双指针技巧的求职者与算法学习者。
9021_TUT_3_25T1
LeetCode 9021. Solution — constructs a string by concatenating repeated structural units, using list generation and string join to decompose the unit structure. Suitable for algorithm beginners and coding interview candidates looking to strengthen foundational string manipulation and divide-and-conquer thinking.