首页 > 其他 > 详细

33. Search in Rotated Sorted Array

时间:2017-10-16 09:26:01      阅读:310      评论:0      收藏:0      [点我收藏+]

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     }

 

33. Search in Rotated Sorted Array

原文:http://www.cnblogs.com/wzj4858/p/7675385.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!