Suppose an array sorted in ascending order 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.
AC代码如下(经典的二分查找变种):
class Solution {
public:
int findMin(vector<int>& nums) {
int left=0;
int right=nums.size()-1;
int mid;
while(nums[left]>nums[right]){
mid=(left+right)/2;
if(nums[mid]>=nums[left])//这个等号必须存在,其他写法类似,但需要特别注意小标以及是否有等号
left=mid+1;
else
right=mid;//这里不需要-1,因为此时mid有可能是最小数,若-1将永远得不到结果
}
return nums[left];
}
};