leetcode 1128.等价多米诺骨牌对的数量
题干
给你一个由一些多米诺骨牌组成的列表 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) 的数量。
示例:
输入:dominoes = [[1,2],[2,1],[3,4],[5,6]]
输出:1
提示:
1 <= dominoes.length <= 40000
1 <= dominoes[i][j] <= 9
题解
将每个骨牌都变为前小后大的状态,然后对整个数组排序后进行统计即可。
值得注意的是,如果存在两个以上相同的骨牌,相同骨牌对的数量应当是组合数。
class Solution {
public:
int combination(int n){
return n * (n - 1) / 2;
}
int numEquivDominoPairs(vector<vector<int>>& dominoes) {
int ans = 0;
for(int i = 0 ; i < dominoes.size() ; ++i){
if(dominoes[i][1] < dominoes[i][0]){
swap(dominoes[i][1],dominoes[i][0]);
}
}
sort(dominoes.begin(),dominoes.end());
int sameCount = 1;
for(int i = 1 ; i < dominoes.size() ; ++i){
if(dominoes[i][0] == dominoes[i - 1][0] && dominoes[i][1] == dominoes[i-1][1]){
sameCount++;
}else{
ans += combination(sameCount);
sameCount = 1;
}
}
ans += combination(sameCount);
return ans;
}
};
(因为骨牌上单个数皆为个位数,所以也可以统一格式后将其拼为一个两位数后用数组统计)