Skip to content

Commit 47513c8

Browse files
authored
Create 1287-element-appearing-more-than-25-in-sorted-array.js
1 parent dbcf4c6 commit 47513c8

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/**
2+
* @param {number[]} arr
3+
* @return {number}
4+
*/
5+
const findSpecialInteger = function (arr) {
6+
const n = arr.length,
7+
{ floor } = Math,
8+
{ getWordIndexRange } = Search()
9+
const ticks = [n / 4, n / 2, (n * 3) / 4].map((e) => floor(e))
10+
for (const i of ticks) {
11+
const [s, e] = getWordIndexRange(arr, arr[i])
12+
if (e - s > n / 4) return arr[i]
13+
}
14+
return 0
15+
}
16+
17+
function Search() {
18+
return { getWordIndexRange }
19+
20+
/**
21+
* Searches for the first true value in the predicate.
22+
* Returns hi if not found.
23+
* [lo, hi)
24+
*/
25+
function binarySearch(lo, hi, predicate) {
26+
while (lo != hi) {
27+
let mid = ((lo + hi) / 2) | 0
28+
if (predicate(mid)) {
29+
hi = mid
30+
} else {
31+
lo = mid + 1
32+
}
33+
}
34+
return lo
35+
}
36+
37+
function getWordIndexRange(keys, word) {
38+
let lo = 0,
39+
hi = keys.length
40+
function greaterOrEqual(index) {
41+
return keys[index] >= word
42+
}
43+
function less(index) {
44+
return keys[index] > word
45+
}
46+
let lower_bound = binarySearch(0, keys.length, greaterOrEqual)
47+
let upper_bound = binarySearch(lower_bound, keys.length, less)
48+
return [lower_bound, upper_bound]
49+
}
50+
}

0 commit comments

Comments
 (0)