-
Notifications
You must be signed in to change notification settings - Fork 0
/
PRO120812.js
42 lines (36 loc) · 937 Bytes
/
PRO120812.js
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
38
39
40
41
42
// Solution 1
function solution1(array) {
const numCountingMap = new Map();
let mode = -1;
let maxCount = 0;
array.forEach((num) => {
numCountingMap.set(num, numCountingMap.has(num) ? numCountingMap.get(num) + 1 : 1);
const countOfNum = numCountingMap.get(num);
if (countOfNum > maxCount) {
maxCount = countOfNum;
mode = num;
} else if (countOfNum === maxCount) {
mode = -1;
}
});
return mode;
}
// Solution 2
function solution2(array) {
const numCounting = array.reduce(
(acc, cur) =>
acc[cur] === undefined
? {
...acc,
[cur]: 1,
}
: {
...acc,
[cur]: acc[cur] + 1,
},
{}
);
const maxCount = Math.max(...Object.values(numCounting));
const modes = Object.keys(numCounting).filter((num) => numCounting[num] === maxCount);
return modes.length === 1 ? Number(modes[0]) : -1;
}