-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdivideAndConcuer.js
More file actions
77 lines (57 loc) · 1.55 KB
/
divideAndConcuer.js
File metadata and controls
77 lines (57 loc) · 1.55 KB
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
function countZeroes(arr) {
let left = 0;
let right = arr.length - 1;
while (left <= right) {
const middle = Math.floor((left + right) / 2);
if (arr[middle] === 1) left = middle + 1;
else right = middle - 1;
}
return arr.length - left;
}
function sortedFrequency(arr, num) {
let left = 0;
let right = arr.length - 1;
while (left <= right) {
const middle = Math.floor((left + right) / 2);
if (arr[middle] === num) {
let leftCount = middle;
let rightCount = middle;
while (arr[leftCount] === num && leftCount >= 0) {
leftCount--;
}
while (arr[rightCount] === num && rightCount < arr.length) {
rightCount++;
}
return rightCount - leftCount - 1;
}
if (arr[middle] < num) left = middle + 1;
else right = middle - 1;
}
return -1;
}
function findRotatedIndex(arr, num) {
let left = 0;
let right = arr.length - 1;
if (right && arr[left] >= arr[right]) {
let middle = Math.floor((left + right) / 2);
while (arr[middle] <= arr[middle + 1]) {
if (arr[left] <= arr[middle]) left = middle + 1;
else right = middle - 1;
middle = Math.floor((left + right) / 2);
}
if (num >= arr[0] && num <= arr[middle]) {
left = 0;
right = middle;
} else {
left = middle + 1;
right = arr.length - 1;
}
}
while (left <= right) {
const middle = Math.floor((left + right) / 2);
if (num === arr[middle]) return middle;
if (num > arr[middle]) left = middle + 1;
else right = middle - 1;
}
return -1;
}