标签:
二分搜索查最小数,from mid to分别为区间的第一个,中位数,和最后一个数
if(from<=mid&&mid<=to)//顺序,第一个即为最小值
return from;
if(from>mid)//发现逆序,则最小值在这个区间,2分搜索区间
to = mid;
if(mid>to)//发现逆序,则最小值在这个区间,2分搜索区间
from = mid;
代码如下:
1 class Solution { 2 public: 3 4 int findMin(vector<int> &num) { 5 int size = num.size(); 6 if(size == 0) 7 return 0; 8 if(size==1) 9 return num[0]; 10 int from = 0; 11 int to = size-1; 12 13 for(int i=0;i<size;i++) 14 { 15 int mid = (from+to)/2; 16 if(num[from]<=num[mid]&&num[mid]<=num[to]) 17 return num[from]; 18 else if(num[from]>num[mid]) 19 { 20 if(from+1 == mid) 21 return num[mid]; 22 to = mid; 23 } 24 else if(num[mid]>num[to]) 25 { 26 if(mid+1==to) 27 return num[to]; 28 from = mid; 29 } 30 } 31 32 } 33 };
Find Minimumd in Rotated Sorted Array
标签:
原文地址:http://www.cnblogs.com/ZhangYushuang/p/4418795.html