Skip to content

Commit 2fd9d84

Browse files
committed
✨ number of equivalent domino pairs
1 parent 0c4bbef commit 2fd9d84

File tree

2 files changed

+31
-29
lines changed

2 files changed

+31
-29
lines changed
Lines changed: 9 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,16 @@
1-
/**
2-
* @param {number[][]} dominoes
3-
* @return {number}
4-
*/
5-
6-
var numEquivDominoPairs = function(dominoes) {
7-
const map = {};
1+
var numEquivDominoPairs = function (dominoes) {
2+
const arr = Array(100).fill(0);
83
let res = 0;
94

10-
for (let pair of dominoes) {
11-
const foo = pair[0] * 10 + pair[1];
12-
const bar = pair[1] * 10 + pair[0];
13-
if (foo === bar) {
14-
map[foo] = ~~map[foo] + 1;
15-
} else {
16-
map[foo] = ~~map[foo] + 1;
17-
map[bar] = ~~map[bar] + 1;
18-
}
19-
}
5+
for (const domino of dominoes) {
6+
const val = Math.min(
7+
domino[0] * 10 + domino[1],
8+
domino[1] * 10 + domino[0]
9+
);
2010

21-
for (let key of Object.keys(map)) {
22-
if (map[key] > 1) {
23-
if (String(key)[0] === String(key)[1]) {
24-
res += (map[key] * (map[key] - 1)) / 2;
25-
} else {
26-
res += (map[key] * (map[key] - 1)) / 4;
27-
}
28-
}
11+
res += arr[val];
12+
arr[val]++;
2913
}
3014

3115
return res;
3216
};
33-
34-
console.log(
35-
numEquivDominoPairs([[1, 1], [2, 2], [1, 1], [1, 2], [1, 2], [1, 1]]),
36-
);
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
/**
2+
* @param {number[][]} dominoes
3+
* @return {number}
4+
*/
5+
var numEquivDominoPairs = function (dominoes) {
6+
const hash = {};
7+
let count = 0;
8+
for (let i = 0; i < dominoes.length; i++) {
9+
const str = dominoes[i].sort().toString();
10+
!hash[str] && (hash[str] = 0);
11+
hash[str]++;
12+
}
13+
14+
const values = Object.values(hash);
15+
for (let j = 0; j < values.length; j++) {
16+
if (values[j] > 1) {
17+
count += (values[j] * (values[j] - 1)) / 2;
18+
}
19+
}
20+
21+
return count;
22+
};

0 commit comments

Comments
 (0)