forked from anishLearnsToCode/leetcode-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
NumberOfEquivalentDominoPairs.java
37 lines (32 loc) · 1.04 KB
/
NumberOfEquivalentDominoPairs.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import java.util.HashMap;
import java.util.Map;
public class NumberOfEquivalentDominoPairs {
private static class Domino {
private final int number;
Domino(int[] array) {
number = Math.min(array[0], array[1]) * 10 + Math.max(array[0], array[1]);
}
@Override
public boolean equals(Object o) {
Domino domino = (Domino) o;
return number == domino.number;
}
@Override
public int hashCode() {
return number;
}
}
public int numEquivDominoPairs(int[][] dominoes) {
final Map<Domino, Integer> dominoesFrequencies = new HashMap<>();
Domino d;
for (int[] domino : dominoes) {
d = new Domino(domino);
dominoesFrequencies.put(d, dominoesFrequencies.getOrDefault(d, 0) + 1);
}
int equivalentPairs = 0;
for (int frequency : dominoesFrequencies.values()) {
equivalentPairs += (frequency * (frequency - 1)) / 2;
}
return equivalentPairs;
}
}