【哈希表】1512. 好数对的数目|2506. 统计相似字符串对的数目
1512. 好数对的数目
1512. 好数对的数目|2506. 统计相似字符串对的数目
class Solution:def numIdenticalPairs(self, nums: List[int]) -> int:ans = 0cnt = 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] += 1return ans