153. Find Minimum in Rotated Sorted Array
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>& nums) {
int lb = 0;
int ub = nums.size() - 1;
//找到有序的区间
while(ub > lb){
//区间有序,返回
if(nums[lb] < nums[ub]) return nums[lb];
int mid = (ub - lb)/2 + lb;
//左半部分有序的话,那么所求的值一定不在左半边
if(nums[mid] >= nums[lb])
lb = mid + 1;
//右半部分有序的话,可能取到mid
else
ub = mid ;
}
return nums[lb];
}
};