1128. 等价多米诺骨牌对的数量
1128. 等价多米诺骨牌对的数量
题目
Given a list of dominoes, dominoes[i] = [a, b] is equivalent todominoes[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 which0 <= i < j < dominoes.length, anddominoes[i]_is equivalent to _dominoes[j].
Example 1:
Input: dominoes = [[1,2],[2,1],[3,4],[5,6]]
Output: 1
Example 2:
Input: dominoes = [[1,2],[1,2],[1,1],[1,2],[2,2]]
Output: 3
Constraints:
1 <= dominoes.length <= 4 * 10^4dominoes[i].length == 21 <= dominoes[i][j] <= 9
题目大意
给你一组多米诺骨牌 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
解题思路
统计出现次数
- 遍历输入数组
dominoes,用哈希表map统计不同多米诺骨牌的出现次数。 - 对于每个骨牌
[a, b],将其键表示为a,b,如果a > b,则交换位置表示为b,a,确保小的数在前。
- 遍历输入数组
计算等价对数
- 如果某种多米诺骨牌出现
n次,那么从这些骨牌中可以组合出C(n, 2) = n * (n - 1) / 2对等价的骨牌。 - 遍历哈希表,累加所有等价对的数量。
- 如果某种多米诺骨牌出现
复杂度分析
- 时间复杂度:
O(n),其中n为dominoes的长度。- 统计多米诺骨牌出现次数:
O(n)。 - 计算等价对数:
O(m),其中m是不等价多米诺骨牌的数量。 - 总时间复杂度为
O(n)。
- 统计多米诺骨牌出现次数:
- 空间复杂度:
O(m),使用了哈希表存储多米诺骨牌和计数。
代码
var numEquivDominoPairs = function (dominoes) {
let map = new Map();
// 统计每种多米诺骨牌的出现次数
for (let [a, b] of dominoes) {
// 等价的多米诺骨牌统一计数
let key = a > b ? `${b},${a}` : `${a},${b}`;
map.set(key, (map.get(key) || 0) + 1);
}
// 计算等价对数
let res = 0;
for (let count of map.values()) {
res += (count * (count - 1)) / 2; // 直接用公式计算
}
return res;
};
