[LeetCode] 1128. Number of Equivalent Domino Pairs

Given a list of dominoesdominoes[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 <= 40000
  • 1 <= dominoes[i][j] <= 9

等价多米诺骨牌对的数量。

给你一个由一些多米诺骨牌组成的列表 dominoes。

如果其中某一张多米诺骨牌可以通过旋转 0 度或 180 度得到另一张多米诺骨牌,我们就认为这两张牌是等价的。

形式上,dominoes[i] = [a, b] 和 dominoes[j] = [c, d] 等价的前提是 a==c 且 b==d,或是 a==d 且 b==c。

在 0 <= i < j < dominoes.length 的前提下,找出满足 dominoes[i] 和 dominoes[j] 等价的骨牌对 (i, j) 的数量。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/number-of-equivalent-domino-pairs
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

既然是判断有多少对牌是等价的牌,那么首先需要用hashmap判断哪些牌的面值是等价的。因为每一张牌上有两个数字,我们可以把这两个数字转换成min * 10 + max,即较小值 * 10 + 较大值。遍历input数组,把所有牌的牌面都存入hashmap时候,在看map.values()有多少。

时间O(n)

空间O(n)

Java实现

 1 class Solution {
 2     public int numEquivDominoPairs(int[][] dominoes) {
 3         HashMap<Integer, Integer> count = new HashMap<>();
 4         int res = 0;
 5         for (int[] d : dominoes) {
 6             int k = Math.min(d[0], d[1]) * 10 + Math.max(d[0], d[1]);
 7             count.put(k, count.getOrDefault(k, 0) + 1);
 8         }
 9         for (int v : count.values()) {
10             res += v * (v - 1) / 2;
11         }
12         return res;
13     }
14 }

 

LeetCode 题目总结 

posted @ 2021-01-27 00:41  CNoodle  阅读(144)  评论(0编辑  收藏  举报