标签:
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
).
Find the minimum element.
You may assume no duplicate exists in the array.
对于Rotated Sorted Array系列,可以考虑用二分法
1 package Find.Minimum.in.Rotated.Sorted.Array; 2 3 /** 4 * @author dell 5 *运用二分查找法进行查找 6 *查询效率为lgN 7 */ 8 public class FindMinimuminRotatedSortedArray { 9 public int findMin(int[] num) { 10 int lo=0; 11 int hi=num.length-1; 12 int mid=lo; 13 if(num.length==1) return num[0]; 14 //可能出现将前面的第0个元素搬到后面,此时整个数组是递增有序的 15 //此时的情况是num[lo]<num[hi] 16 while(num[lo]>=num[hi]){ 17 //当hi-lo=1时此时的hi为第二个递增数组的第一个元素,即为最小元素 18 if(hi-lo==1){ 19 mid=hi; 20 break; 21 } 22 mid=(lo+hi)/2; 23 if(num[mid]<num[lo]) hi=mid; 24 else lo=mid; 25 } 26 return num[mid]; 27 } 28 public static void main(String args[]){ 29 FindMinimuminRotatedSortedArray service=new FindMinimuminRotatedSortedArray(); 30 //int[] a={4,5,6,7,0,1,2}; 31 int a[]={1,2}; 32 int result=service.findMin(a); 33 System.out.println(result); 34 } 35 }
Leetcode Find Minimum in Rotated Sorted Array
标签:
原文地址:http://www.cnblogs.com/criseRabbit/p/4317655.html