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.
Subscribe to see which companies asked this question.
题意:找出升序数组旋转后最小值。旋转后的数组分三种情况
0 1 2 4 5 6 7
7 0 1 2 4 5 6
4 5 6 7 0 1 2
都有个特性,因为是升序所以,当nums[mid] < nums[r]的时候最小值肯定在左边了
class Solution {
public:
int findMin(vector<int>& nums) {
int l, r, mid;
l = 0, r = nums.size() - 1;
while(l <= r){
mid = l + (r - l) / 2;
if(nums[mid] < nums[r]){
r = mid;
} else if(nums[mid] > nums[r]){
l = mid + 1;
} else if(nums[mid] == nums[r])
break;
}
return nums[l];
}
};