[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 };
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值