-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0033-SearchInRotatedSortedArray.js
54 lines (46 loc) · 1.39 KB
/
0033-SearchInRotatedSortedArray.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
//-----------------------------------------------------------------------------
// Runtime: 68ms
// Memory Usage: 36.5 MB
// Link: https://leetcode.com/submissions/detail/385840085/
//-----------------------------------------------------------------------------
var solution = function() {
'use strict';
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var search = function(nums, target) {
let lo = 0, hi = nums.length - 1;
while (lo <= hi) {
let loValue = nums[lo],
hiValue = nums[hi];
if (loValue <= hiValue && (target < loValue || target > hiValue)) {
return -1;
}
let mid = Math.floor(lo + (hi - lo) / 2);
let midValue = nums[mid];
if (midValue === target) {
return mid;
}
if (loValue <= midValue) {
if (loValue <= target && target < midValue) {
hi = mid - 1;
} else {
lo = mid + 1;
}
} else {
if (target <= hiValue && midValue < target) {
lo = mid + 1;
} else {
hi = mid - 1;
}
}
}
return -1;
};
return {
search: search
};
};
module.exports = solution();