内卷地狱

Python beat98.40% collectionsofCounter method!

Edit Me

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})

  1. So traverse a dictionary,whenvalue>3of时候value=2,Can be greater than2indivualof元素计数become2indivual。
  2. So we willCounter({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.0CCBYNCSA