forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0033-search-in-rotated-sorted-array.js
44 lines (35 loc) · 1.22 KB
/
0033-search-in-rotated-sorted-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
/**
* @param {number[]} nums
* @param {number} target
* Time O(log(N)) | Space O(1)
* @return {number}
*/
var search = (nums, target) => {
let [left, right] = [0, nums.length - 1];
while (left <= right) {
const mid = (left + right) >> 1;
const guess = nums[mid];
const [leftNum, rightNum] = [nums[left], nums[right]];
const isTarget = guess === target;
if (isTarget) return mid;
const isAscending = leftNum <= guess;
if (isAscending) {
const isInRange = leftNum <= target;
const isLess = target < guess;
const isTargetGreater = !(isInRange && isLess);
if (isTargetGreater) left = mid + 1;
const isTargetLess = isInRange && isLess;
if (isTargetLess) right = mid - 1;
}
const isDescending = guess < leftNum;
if (isDescending) {
const isGreater = guess < target;
const isInRange = target <= rightNum;
const isTargetGreater = isGreater && isInRange;
if (isTargetGreater) left = mid + 1;
const isTargetLess = !(isGreater && isInRange);
if (isTargetLess) right = mid - 1;
}
}
return -1;
};