Python beat98.40% collectionsofCounter method!
Pyhton collection In the bag Counter() Be rightlist里出现of元素conduct计数,And the output is a dictionary。
for examplenums=[1, 1, 1, 2, 2, 3] ToCounter后of结果是Counter({1: 3, 2: 2, 3: 1})。
- So traverse a dictionary,when
value>3of时候value=2,Can be greater than2indivualof元素计数become2indivual。 - So we will
Counter({1: 3, 2: 2, 3: 1})becomeCounter({1: 2, 2: 2, 3: 1})后再Toelementsconductlist操作就可以得到改变后of列表了。
Due to the meaning of the question“Input the array「Quote」方式传递of”,So we willnumsJust fill in and fill in
from collections import Counter # Imported package
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 the collection to the list
return len(nums)Complexity analysis
time complexity:O(n),in n 是数组of长度。We have a maximum of this array once。
Spatial complexity:O(1)。我们只需要常数of空间存储若干变量。
贡献者
最近更新
Involution Hell© 2026 byCommunityunderCC BY-NC-SA 4.0
76Minimum cover string.md
LeetCode 76. 最小覆盖子串 题解 — 滑动窗口 + 双指针 + 哈希表计数,通过右指针扩展窗口、左指针收缩窗口,动态维护字符频次字典以判断是否覆盖目标串 t。适合准备面试、刷 LeetCode 的 CS/AI 求职者与算法学习者阅读。
80. Remove Duplicates from Sorted Array II — Python beats 98.40% using collections.Counter!
LeetCode 80. Remove Duplicates from Sorted Array II — Uses collections.Counter to cap element frequencies at 2, then modifies the array in-place. For Python developers seeking an O(n) time, O(1) space solution.