一.问题描述
Given a list of dominoes, dominoes[i] = [a, b] is equivalent to dominoes[j] = [c, d] if and only if either (a==c and b==d), or (a==d and b==c) - that is, one domino can be rotated to be equal to another domino.
Return the number of pairs (i, j) for which 0 <= i < j < dominoes.length, and dominoes[i] is equivalent to dominoes[j].
Example 1:
Input: dominoes = [[1,2],[2,1],[3,4],[5,6]]
Output: 1
Constraints:
1 <= dominoes.length <= 400001 <= dominoes[i][j] <= 9
二.解题思路
这道题注意pair是j>i, 因此我们值需要顺序遍历即可
因为只要是equivalent的,那么将他们排序后,他们两组成的十位数是唯一的,可以用来映射,用字典保存该equivalent的pair对个数。
比如说[1,2],[2,1],他们的唯一十位数是12,可以用来映射,因为每个pari组成的十位数都不同。
遍历到一个新的pair,首先排序,然后变成十位数,之后通过字典判断是否有equivalent的数并且个数
若有的话则在原来的个数上+1就是新加的pair对个数。
具体请看源码。
更多leetcode算法题解法请关注我的专栏leetcode算法从零到结束或关注我
欢迎大家一起套路一起刷题一起ac。
三.源码
class Solution:
def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:
cnt = collections.defaultdict(int)
ans = 0
for a, b in dominoes:
if a > b: a, b = b, a
v = 10*a + b
ans+=cnt.get(v,0)
cnt[v] += 1
return ans
本文介绍了一种高效算法,用于解决给定多米诺骨牌列表中等效多米诺骨牌对数量的问题。通过将每个多米诺骨牌排序并转换为十位数进行映射,利用字典保存等效多米诺骨牌对的数量,从而快速计算出所有等效对。此方法适用于LeetCode算法题解。
797

被折叠的 条评论
为什么被折叠?



