You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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].
Given a list of
dominoes
,dominoes[i] = [a, b]
is equivalent todominoes[j] = [c, d]
if and only if either (a==c
andb==d
), or (a==d
andb==c
) - that is, one domino can be rotated to be equal to another domino.Return the number of pairs
(i, j)
for which0 <= i < j < dominoes.length
, anddominoes[i]
is equivalent todominoes[j]
.Example 1:
Constraints:
1 <= dominoes.length <= 40000
1 <= dominoes[i][j] <= 9
这道题给了一个多米诺数组,每个多米诺有两个数字,现在让找有多少个相同的多米诺,由于多米诺可以旋转,所以这里两个数字的顺序并不重要。虽然说是一道简单的题目,但是暴力搜索法还是不可取的,太不高效了,最好的还是直接统计相同的牌的数量,再来计算相同的 pair 对儿个数。若多米诺不能翻转,直接进行统计就行了,现在能翻转,就要统一用个方法来标记翻转后相同的多米诺,这里可以始终将小的放在前面。又由于数字只有1到9,所以可以把较小的数字编码到十位上,较大的数字编码到个位上,这样组成的两位数就可以表示独特的多米诺了。统计完相同的多米诺个数之后就可以计算相同的 pair 对儿了,若有n个相同的多米诺,则共有
n(n-1)/2
个相同的 pair 对儿,这样就可以算出总共相同的 pair 对儿个数了,参见代码如下:解法一:
其实我们不用在最后单独计算 pair 对儿的个数,而是可以边统计边累加,当计算出某个多米诺的编码值之后,可以将其在 HashMap 中的映射值直接加到结果 res 中(若从未出现过,则加上的是0,不影响结果),然后再将其映射值加1,这里表示当前新的这个多米诺可以跟之前所有的多米诺都组成一个新的 pair 对儿,参见代码如下:
解法二:
Github 同步地址:
#1128
参考资料:
https://leetcode.com/problems/number-of-equivalent-domino-pairs/
https://leetcode.com/problems/number-of-equivalent-domino-pairs/discuss/340022/JavaC%2B%2BPython-Easy-and-Concise
https://leetcode.com/problems/number-of-equivalent-domino-pairs/discuss/339969/JavaPython-3-O(n)-code-with-brief-explanation-and-analysis.
LeetCode All in One 题目讲解汇总(持续更新中...)
The text was updated successfully, but these errors were encountered: