-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcomplexity.js
111 lines (87 loc) · 2.7 KB
/
complexity.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/* Поиск наиболее часто встречающихся элементов в массиве */
const arr = ['a', 'b', 'a', 'b', 'b'];
/* 1. Перебор всех значений в лоб.
Сложность по времени: N**2; сложность по памяти: N. */
function notEffectiveGetRepeats(list){
let sym = '';
let counter = 0;
for(let i = 0; i < list.length; i++){
let currentSym = list[i];
let currentCounter = 0;
for(let j = 0; j < list.length; j++){
if(currentSym === list[j])
currentCounter++;
}
if(currentCounter > counter){
sym = currentSym;
counter = currentCounter;
}
}
return {
sym,
counter
}
}
/* 2. Фильтрация уникальных значений через new Set() и их сравнение
cо всеми позициями в массиве.
Сложность по времени: N * K = N**2; сложность по памяти: N + K = N. */
function moreEffectiveGetRepeats(list){
let sym = '';
let counter = 0;
const uniq = Array.from(new Set(list));
for(let i = 0; i < uniq.length; i++){
const currentSym = uniq[i];
let currentCounter = 0;
for(let j = 0; j < list.length; j++){
if(currentSym === list[j])
currentCounter++;
}
if(currentCounter > counter){
counter = currentCounter;
sym = currentSym;
}
}
return {
sym,
counter
}
}
/* 3. Внесение элементов массива в объект, где ключи равны этим
элементам, а значения - количество повторений.
Сложность по времени: N;
сложность по памяти: K (если строки приходит посимвольно). */
function getRepeats(list){
const repeats = {};
let sym = '';
let counter = 0;
for(let i = 0; i < list.length; i++){
const now = list[i];
if(!repeats[now])
repeats[now] = 0;
++repeats[now];
}
for(let key in repeats){
if(repeats[key] > counter){
sym = key;
counter = repeats[key];
}
}
return {
sym,
counter
};
}
notEffectiveGetRepeats(arr);
moreEffectiveGetRepeats(arr);
getRepeats(arr);
const sequence = [-1, 2, 4];
function getMax (seq){
if(!seq.length) return -Infinity;
let max = seq[0];
for(let i = 1; i < seq.length; i++){
if(seq[i] > max)
max = seq[i];
}
return max
}
getMax(sequence)