-
Notifications
You must be signed in to change notification settings - Fork 0
/
lesson8.js
74 lines (59 loc) · 1.71 KB
/
lesson8.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
64
65
66
67
68
69
70
71
72
73
74
//eQui leader, divisions of arrays that have same leader
function findMostCommon(array) {
var map = {};
var maxCount = 1;
var maxElem;
if (array.length === 1) (maxElem = array[0]);
for (x = 0; x < array.length; x++) {
if (map[array[x]] === undefined) {
map[array[x]] = 1;
} else {
map[array[x]] = map[array[x]] + 1;
if (map[array[x]] > maxCount) {
maxCount = map[array[x]];
maxElem = array[x];
}
}
}
if (maxCount >= (Math.floor(array.length / 2) + 1)) {
return maxElem;
} else {
return undefined;
}
}
function solution(A) {
var count = 0;
for (i = 0; i < A.length - 1; i++) {
var first = A.slice(0, i + 1);
var second = A.slice(i + 1, A.length);
var elemFirst = findMostCommon(first);
var elemSecond = findMostCommon(second);
if (elemFirst !== undefined && elemSecond !== undefined) {
if ((elemFirst === elemSecond)) (count++);
}
}
return count;
}
//return index of leader if there is any in array
function solution(array) {
var map = {};
var maxCount = 1;
var maxElem;
if (array.length === 1) (maxElem = array[0]);
for (x = 0; x < array.length; x++) {
if (map[array[x]] === undefined) {
map[array[x]] = 1;
} else {
map[array[x]] = map[array[x]] + 1;
if (map[array[x]] > maxCount) {
maxCount = map[array[x]];
maxElem = array[x];
}
}
}
if (maxCount >= (Math.floor(array.length / 2) + 1)) {
return array.indexOf(maxElem);
} else {
return -1;
}
}