1512. 好数对的数目
class Solution:
def numIdenticalPairs(self, nums: List[int]) -> int:
ans = 0
cnt = defaultdict(int)
for x in nums: # x = nums[j]
# 此时 cnt[x] 表示之前遍历过的 x 的个数,加到 ans 中
# 如果先执行 cnt[x] += 1,再执行 ans += cnt[x],就把 i=j 这种情况也统计进来了,算出的答案会偏大
ans += cnt[x]
cnt[x] += 1
return ans