search-in-rotated-sorted-array
1.0.0
Search in Rotated Sorted Array
Loading...
Searching...
No Matches
main.cpp
Go to the documentation of this file.
1
#include <bits/stdc++.h>
2
3
using namespace
std;
4
5
class
Solution
6
{
7
public
:
8
int
search
(vector<int>& nums,
int
target)
9
{
10
int
left = 0;
11
int
right = (int)nums.size() - 1;
12
while
(left <= right)
13
{
14
int
mid = (left + right) / 2;
15
if
(target == nums[mid])
16
return
mid;
17
18
if
(nums[mid] >= nums[left])
// subarray to the left of mid is sorted, rotation may occur in the right side
19
{
20
if
(target > nums[mid] || target < nums[left])
21
left = mid + 1;
// go right
22
else
23
right = mid - 1;
// go left
24
}
25
else
// subarray to the right of mid is sorted, rotation may occur in the left side
26
{
27
if
(target < nums[mid] || target > nums[right])
28
right = mid - 1;
// go left
29
else
30
left = mid + 1;
// go right
31
}
32
}
33
return
-1;
34
}
35
};
36
37
int
main
()
38
{
39
vector<int> nums = {4,5,6,7,0,1,2};
40
int
target = 0;
41
cout <<
"output: "
<<
Solution
().
search
(nums, target) << endl;
42
return
0;
43
}
Solution
Definition
main.cpp:6
Solution::search
int search(vector< int > &nums, int target)
Definition
main.cpp:8
main
int main()
Definition
main.cpp:37
main.cpp
Generated by
1.9.8