-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathdominator.js
63 lines (54 loc) · 1.08 KB
/
dominator.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// with stack
function solution(A) {
const N = A.length;
const stack = [];
for (let i = 0; i < N; i++) {
if (stack.length === 0 || stack[stack.length - 1] === A[i]) {
stack.push(A[i]);
} else {
stack.pop();
}
}
if (stack.length > 0) {
const candidate = stack.pop();
const minCount = Math.floor(N / 2) + 1;
let count = 0;
for (let i = 0; i < N; i++) {
if (A[i] === candidate) {
count++;
if (count >= minCount) {
return i;
}
}
}
}
return -1;
}
// with map
function solution(A) {
const N = A.length;
const map = {};
for (let i = 0; i < N; i++) {
if (map[A[i]]) {
map[A[i]]++;
} else {
map[A[i]] = 1;
}
}
let maxCount = 0;
let candidate = undefined;
for (const [value, count] of Object.entries(map)) {
if (count > maxCount) {
maxCount = count;
candidate = parseInt(value);
}
}
if (maxCount >= Math.floor(N / 2) + 1) {
for (let i = 0; i < N; i++) {
if (A[i] === candidate) {
return i;
}
}
}
return -1;
}