Posted on 2023-10-03 16:45
Uriel 閱讀(40)
評論(0) 編輯 收藏 引用 所屬分類:
閑來無事重切Leet Code 、
大水題
給出一列數,問滿足nums[i] == nums[j] and i < j的i,j pair有多少個,其實就是計算每種數字的出現次數,然后求其中選2個的組合數,再求和,直接用python的Counter
1 #1512
2 #Runtime: 21 ms (Beats 23.47%)
3 #Memory: 13.3 MB (Beats 40.52%)
4
5 class Solution(object):
6 def numIdenticalPairs(self, nums):
7 """
8 :type nums: List[int]
9 :rtype: int
10 """
11 return sum(i * (i - 1) // 2 for i in Counter(nums).values())