码迷,mamicode.com
首页 > 其他好文 > 详细

33. Search in Rotated Sorted Array

时间:2017-10-16 09:45:38      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:一个   otherwise   旋转   排序   unknown   dict   order   array   exists   

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

标签:一个   otherwise   旋转   排序   unknown   dict   order   array   exists   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!