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.
1、二分查找
int findMin(vector<int> &num) {
if(num.at(0)<num.at(num.size()-1)) return num.at(0);
int low=0;
int high=num.size()-1;
int mid=0;
while(low<high)
{
mid=(low+high)/2;
if(num.at(mid)>num.at(high))
{
low=mid+1;
}
else
{
high=mid;
}
}
return num.at(low);
}
2、顺序查找
int findMin(vector<int> &num) {
if(num.size()==1||num.at(0)<num.at(num.size()-1)) return num.at(0);
int index=1;
while(index<num.size()&&num.at(index)>num.at(index-1))
{
index++;
}
return num.at(index);
}