Skip to content

Commit 322b54d

Browse files
committed
feat: 33. Search in Rotated Sorted Array
1 parent 2ffc9a0 commit 322b54d

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// Time complexity: O(logn)
2+
// Space complexity: O(1)
3+
4+
/**
5+
* @param {number[]} nums
6+
* @param {number} target
7+
* @return {number}
8+
*/
9+
var search = function (nums, target) {
10+
let left = 0;
11+
let right = nums.length - 1;
12+
13+
while (left <= right) {
14+
const mid = Math.floor((left + right) / 2);
15+
16+
if (nums.at(mid) === target) {
17+
return mid;
18+
}
19+
20+
// rotate 된 구간이 있을 때
21+
if (nums.at(mid + 1) > nums.at(right)) {
22+
if (nums.at(right) >= target || nums.at(mid + 1) <= target) {
23+
left = mid + 1;
24+
continue;
25+
}
26+
27+
right = mid - 1;
28+
continue;
29+
}
30+
31+
if (target >= nums.at(mid + 1) && target <= nums.at(right)) {
32+
left = mid + 1;
33+
continue;
34+
}
35+
36+
right = mid - 1;
37+
}
38+
39+
return -1;
40+
};

0 commit comments

Comments
 (0)