【LeetCode】33. Search in Rotated Sorted Array

Suppose an array sorted in ascending order 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.

题意:在旋转的已排序数组中找出特定值的索引

思路:1.用二分法找出数组中最小值的索引

  2.用最小值把数组分为两部分,确定特定值在哪个部分,然后对单独的一个部分利用二分法

(感觉这个思路比《剑指OFFER》上面的那个思路容易理解)

 1 int search(int* nums, int numsSize, int target) {
 2     int lo=0,hi=numsSize-1,mid;
 3     while(lo<hi){
 4         mid=(lo+hi)/2;
 5         if(nums[mid]>nums[hi])
 6             lo=mid+1;
 7         else
 8             hi=mid;
 9     }
10     if(nums[numsSize-1]>=target)
11         hi=numsSize-1;
12     else{
13         hi=lo-1;
14         lo=0;
15     }
16     while(lo<=hi){
17         mid=(lo+hi)/2;
18         if(target>nums[mid]) lo=mid+1;
19         else if(target<nums[mid]) hi=mid-1;
20         else return mid;
21     }
22     return -1;
23 }

 另外,讨论区的另外两种做法让人佩服死了。。。膜拜一下

posted @ 2017-01-17 10:41  wilderness  阅读(158)  评论(0编辑  收藏  举报