search-in-rotated-sorted-array 1.0.0
Search in Rotated Sorted Array
Loading...
Searching...
No Matches
Solution Class Reference

Public Member Functions

int search (vector< int > &nums, int target)
 

Detailed Description

Definition at line 5 of file main.cpp.

Member Function Documentation

◆ search()

int Solution::search ( vector< int > &  nums,
int  target 
)
inline

Definition at line 8 of file main.cpp.

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 }

Referenced by main().


The documentation for this class was generated from the following file: