1128.等价多米诺骨牌对的数量
hash table, https://leetcode.cn/problems/number-of-equivalent-domino-pairs/
给你一组多米诺骨牌 dominoes 。
形式上,dominoes[i] = [a, b] 与 dominoes[j] = [c, d] 等价 当且仅当 (a == c 且 b == d) 或者 (a == d 且 b == c) 。即一张骨牌可以通过旋转 0 度或 180 度得到另一张多米诺骨牌。
在 0 <= i < j < dominoes.length 的前提下,找出满足 dominoes[i] 和 dominoes[j] 等价的骨牌对 (i, j) 的数量。
示例 1:
输入:dominoes = [[1,2],[2,1],[3,4],[5,6]]
输出:1示例 2:
输入:dominoes = [[1,2],[1,2],[1,1],[1,2],[2,2]]
输出:3提示:
1 <= dominoes.length <= 4 * 10^4dominoes[i].length == 21 <= dominoes[i][j] <= 9
python
from collections import defaultdict
from typing import List
class Solution:
def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:
count = defaultdict(int)
for a, b in dominoes:
key = (a, b) if a <= b else (b, a)
count[key] += 1
ans = 0
for v in count.values():
if v > 1:
ans += v * (v - 1) // 2
return ans