Python计数:defaultdict和Counter
使用Python内置的defaultdict和Counter能方便的实现计数等操作
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