forked from everthis/leetcode-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
1095-find-in-mountain-array.js
66 lines (64 loc) · 1.47 KB
/
1095-find-in-mountain-array.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
/**
* // This is the MountainArray's API interface.
* // You should not implement it, or speculate about its implementation
* function MountainArray() {
*
* @param {integer} index
* @return {integer}
* this.get = function(index) {
* ...
* };
*
* @return {integer}
* this.length = function() {
* ...
* };
* };
*/
/**
* @param {number} target
* @param {MountainArray} mountainArr
* @return {number}
*/
const findInMountainArray = function(target, mountainArr) {
const p = findPeak(mountainArr)
if (mountainArr.get(p) === target) {
return p
}
const left = binarySeach(mountainArr, 0, p, target, 'asc')
if (left > -1) {
return left
}
return binarySeach(mountainArr, p + 1, mountainArr.length(), target, 'dsc')
}
function findPeak(arr) {
let left = 0
let right = arr.length()
while (left < right) {
const mid = Math.floor((left + right) / 2)
if (arr.get(mid) < arr.get(mid + 1)) {
left = mid + 1
} else {
right = mid
}
}
return left
}
function binarySeach(mountainArr, start, end, target, order) {
let left = start
let right = end
while (left < right) {
const mid = Math.floor((left + right) / 2)
if (target === mountainArr.get(mid)) {
return mid
} else if (
(target > mountainArr.get(mid) && order === 'asc') ||
(target < mountainArr.get(mid) && order === 'dsc')
) {
left = mid + 1
} else {
right = mid
}
}
return -1
}