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 <= 40000
1 <= dominoes[i][j] <= 9
这题类似于排序,只是坐标之间反的也是相等的。那么我们按照这个规则进行排序后计算一下重复的个数即可。
class NumberOfEquivalentDominoPairs : public Solution {
public:
void Exec() {
vector<vector<int>> input;
input.push_back(vector<int>{1,2});
input.push_back(vector<int>{1,2});
input.push_back(vector<int>{1,1});
input.push_back(vector<int>{1,2});
input.push_back(vector<int>{2,2});
auto res = numEquivDominoPairs(input);
}
int numEquivDominoPairs(vector<vector<int>>& dominoes) {
int res = 0;
std::sort(dominoes.begin(), dominoes.end(), [](vector<int> &a, vector<int> &b) -> bool {
if (a[0] > a[1]) {
std::swap(a[0], a[1]);
}
if (b[0] > b[1]) {
std::swap(b[0], b[1]);
}
if (a[0] == b[0]) {
return a[1] < b[1];
}
return a[0] < b[0];
});
int conts = 0;
for (int i = 1; i <= dominoes.size(); i++) {
if (i < dominoes.size() && dominoes[i][0] == dominoes[i - 1][0] &&
dominoes[i][1] == dominoes[i - 1][1]) {
conts++;
} else {
if (conts != 0) {
res += conts * (1 + conts) / 2;
}
conts = 0;
}
}
return res;
}
};