Python计数:defaultdict和Counter

使用Python内置的defaultdict和Counter能方便的实现计数等操作

题目:3289. 数字小镇中的捣蛋鬼

from typing import List
from collections import defaultdict, Counter

class Solution:
    def getSneakyNumbers(self, nums: List[int]) -> List[int]:
        counter = Counter(nums)
        ans = []
        for key in counter:
            if counter[key] > 1:
                ans.append(key)
        return ans
    
    def getSneakyNumbers(self, nums: List[int]) -> List[int]:
        ans = []
        d = defaultdict(int)  # 键不存在时调用int()返回0
        for i in nums:
            d[i] += 1
            if d[i] > 1:
                ans.append(i)
        return ans
posted @ 2024-09-15 14:05  faf4r  阅读(5)  评论(0编辑  收藏  举报