[LeetCode] Search in Rotated Sorted Array

Suppose a sorted array is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

You are given a target value to search. If found in the array return its index, otherwise return -1.

You may assume no duplicate exists in the array.

二分搜索来找到转折点,也就是最小数的位置。对二分搜索要稍作修改,当a[left] <= a[mid]时,可以肯定a[left..mid]是升序的,那么a[left]是最小的,也肯能最小的在a[mid+1..right]中,

所以要比较a[left]和min(a[mid+1..right]),同样对于a[left]>a[mid],做同样的处理。

 1 class Solution {
 2 public:
 3     int findPos(int a[], int left, int right)
 4     {
 5         if (left > right)
 6             return -1;
 7             
 8         int mid = left + (right - left) / 2;
 9         
10         if (a[left] <= a[mid])
11         {
12             int pos = findPos(a, mid + 1, right);
13             
14             if (pos == -1)
15                 return left;
16             else
17                 return a[left] < a[pos] ? left : pos; 
18         }
19         else
20         {
21             int pos = findPos(a, left, mid - 1);
22             
23             if (pos == -1)
24                 return mid;
25             else
26                 return a[pos] < a[mid] ? pos : mid;
27         }
28     }
29     
30     int bsearch(int a[], int left, int right, int key)
31     {
32         if (left > right)
33             return -1;
34             
35         int mid = left + (right - left) / 2;
36         
37         if (a[mid] == key)
38             return mid;
39         else if (a[mid] < key)
40             return bsearch(a, mid + 1, right, key);
41         else
42             return bsearch(a, left, mid - 1, key);
43     }
44     
45     int search(int A[], int n, int target) {
46         // Start typing your C/C++ solution below
47         // DO NOT write int main() function
48         int pos = findPos(A, 0, n - 1);
49         
50         int index = bsearch(A, 0, pos - 1, target);
51         if (index != -1)
52             return index;
53             
54         return bsearch(A, pos, n - 1, target);
55     }
56 };
原文地址:https://www.cnblogs.com/chkkch/p/2770586.html