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.

假设有一个排序的按未知的旋转轴旋转的数组(比如,0 1 2 4 5 6 7 可能成为4 5 6 7 0 1 2)。给定一个目标值进行搜索,如果在数组中找到目标值返回数组中的索引位置,否则返回-1。

 1     public int search(int[] nums, int target) {
 2         int n = nums.length;
 3         int lo=0,hi=n-1;
 4         // find the index of the smallest value using binary search.
 5         // Loop will terminate since mid < hi, and lo or hi will shrink by at least 1.
 6         // Proof by contradiction that mid < hi: if mid==hi, then lo==hi and loop would have been terminated.
 7         while(lo<hi){
 8             int mid=(lo+hi)/2;
 9             if(nums[mid]>nums[hi]) lo=mid+1;
10             else hi=mid;
11         }
12         // lo==hi is the index of the smallest value and also the number of places rotated.
13         int rot=lo;
14         lo=0;hi=n-1;
15         // The usual binary search and accounting for rotation.
16         while(lo<=hi){
17             int mid=(lo+hi)/2;
18             int realmid=(mid+rot)%n;
19             if(nums[realmid]==target)return realmid;
20             if(nums[realmid]<target)lo=mid+1;
21             else hi=mid-1;
22         }
23         return -1;
24     }

 

posted @ 2017-10-16 07:58  daniel456  阅读(132)  评论(0编辑  收藏  举报