File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed
search-in-rotated-sorted-array Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public:
3
+ int search (vector<int >& nums, int target) {
4
+ int left = 0 ;
5
+ int right = nums.size () - 1 ;
6
+ while (left <= right) {
7
+ int mid = left + (right - left) / 2 ;
8
+
9
+ if (nums[mid] == target)
10
+ return (mid);
11
+
12
+ // 왼쪽 구간이 정렬된 상태일 때
13
+ if (nums[left] <= nums[mid]) {
14
+ // 왼쪽 구간에 있으면 right를 좁히면서 target을 탐색
15
+ if (nums[left] <= target && target < nums[mid]) {
16
+ right = mid - 1 ;
17
+ }
18
+ // 왼쪽 구간에 없다면 오른쪽 구간으로 이동
19
+ else
20
+ left = mid + 1 ;
21
+ }
22
+ // 오른쪽 구간이 정렬된 상태
23
+ else {
24
+ // 오른쪽 구간에 target이 있으면 left를 좁히면서 target 탐색
25
+ if (nums[mid] < target && target <= nums[right]) {
26
+ left = mid + 1 ;
27
+ }
28
+ // 오른쪽 구간에 없다면 왼쪽 구간으로 이동
29
+ else
30
+ right = mid - 1 ;
31
+ }
32
+ }
33
+ return (-1 );
34
+ }
35
+ };
You can’t perform that action at this time.
0 commit comments