LeetCode Q 1128 - Number of Equivalent Domino Pairs
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:
Solution:
- Traverse the dominoes array, count the number of same pairs.
- Use Combination to get the result.
Code:
public int numEquivDominoPairs(int[][] dominoes) {
Map<Integer, Integer> map = new HashMap<>();
for (int d: dominoes) {
int a = d[0], b = d[1];
int key = Math.max(a, b) * 10 + Math.min(a, b);
map.put(key, map.getOrDefault(key, 0) + 1);
}
int res = 0;
for (int key: map.keySet()) {
int v = map.get(key);
res += v * (v - 1) / 2;
}
return res;
}