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.
好像是挺常见的面试题,使用的是二分查找
class Solution {
public:
int findMin(vector<int> &num) {
int l = 0, r = num.size()-1;
while( l < r ){
int mid = (l+r)/2;
if( num[l] <= num[mid] && num[mid] <= num[r] ){
break;
}else if( num[mid] > num[r]){
//如果num[mid]比num[r]大,那么最小值一定在[mid+1,r]中
l = mid + 1 ;
}else{
//如果num[mid]比num[r]小,那么最小值一定在[l,mid]中
//如(4,5,1,2,3)
r = mid;
}
}
return num[l];
}
};