Skip to content

Commit 0ec235a

Browse files
committed
search in rotated sorted array solution
1 parent 929d8d9 commit 0ec235a

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
function search(nums: number[], target: number): number {
2+
let left = 0;
3+
let right = nums.length - 1;
4+
5+
while (left <= right) {
6+
const mid = Math.floor((left + right) / 2);
7+
8+
if (nums[mid] === target) return mid;
9+
10+
if (nums[mid] >= nums[left]) {
11+
if (target < nums[mid] && target >= nums[left]) {
12+
right = mid - 1;
13+
} else {
14+
left = mid + 1;
15+
}
16+
} else {
17+
if (target > nums[mid] && target <= nums[right]) {
18+
left = mid + 1;
19+
} else {
20+
right = mid - 1;
21+
}
22+
}
23+
}
24+
25+
return -1;
26+
}

0 commit comments

Comments
 (0)