使用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