Skip to content

Commit fed97ea

Browse files
committed
solve: search in rotated sorted array
1 parent e5a39ef commit fed97ea

File tree

1 file changed

+38
-0
lines changed
  • search-in-rotated-sorted-array

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* @param {number[]} nums
3+
* @param {number} target
4+
* @return {number}
5+
*/
6+
var search = function (nums, target) {
7+
let leftIndex = 0;
8+
let rightIndex = nums.length - 1;
9+
10+
while (leftIndex <= rightIndex) {
11+
const midIndex = Math.floor((rightIndex + leftIndex) / 2);
12+
const [leftValue, midValue, rightValue] = [
13+
nums[leftIndex],
14+
nums[midIndex],
15+
nums[rightIndex],
16+
];
17+
18+
if (midValue === target) {
19+
return midIndex;
20+
}
21+
22+
if (leftValue <= midValue) {
23+
if (leftValue <= target && target < midValue) {
24+
rightIndex = midIndex - 1;
25+
} else {
26+
leftIndex = midIndex + 1;
27+
}
28+
} else {
29+
if (midValue < target && target <= rightValue) {
30+
leftIndex = midIndex + 1;
31+
} else {
32+
rightIndex = midIndex - 1;
33+
}
34+
}
35+
}
36+
37+
return -1;
38+
};

0 commit comments

Comments
 (0)