Skip to content

Commit ece842c

Browse files
committed
solve: search in rotated sorted array
1 parent 01ae490 commit ece842c

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
/**
2+
* TC: O(log N)
3+
* 이진탐색을 이용하여 순회합니다.
4+
*
5+
* SC: O(1)
6+
* 이진탐색에 이용되는 투 포인터의 공간복잡도를 갖습니다.
7+
*/
8+
9+
/**
10+
* @param {number[]} nums
11+
* @param {number} target
12+
* @return {number}
13+
*/
14+
var search = function (nums, target) {
15+
if (nums.length === 1) {
16+
return target === nums[0] ? 0 : -1;
17+
}
18+
19+
let left = 0;
20+
let right = nums.length - 1;
21+
22+
while (left < right) {
23+
const center = Math.floor((left + right) / 2);
24+
if (target === nums[left]) {
25+
return left;
26+
}
27+
if (target === nums[center]) {
28+
return center;
29+
}
30+
if (target === nums[right]) {
31+
return right;
32+
}
33+
34+
if (nums[left] <= nums[center] && nums[center] < nums[right]) {
35+
if (target < nums[left] || nums[right] < target) {
36+
return -1;
37+
} else if (nums[left] < target && target < nums[center]) {
38+
right = center;
39+
} else if (nums[center] < target && target < nums[right]) {
40+
left = center + 1;
41+
}
42+
} else if (nums[right] < nums[left] && nums[left] <= nums[center]) {
43+
if (nums[right] < target && target < nums[left]) {
44+
return -1;
45+
} else if (nums[left] < target && target < nums[center]) {
46+
right = center;
47+
} else {
48+
left = center + 1;
49+
}
50+
} else if (nums[center] < nums[right] && nums[right] < nums[left]) {
51+
if (nums[center] < target && target < nums[right]) {
52+
left = center + 1;
53+
} else if (nums[right] < target && target < nums[left]) {
54+
return -1;
55+
} else {
56+
right = center;
57+
}
58+
}
59+
}
60+
61+
return -1;
62+
};

0 commit comments

Comments
 (0)