Problem
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.
Solution
一开始看题目以为是确定这个数组在某一个点旋转了,跑了一下才发现也有可能没有旋转,完全是一个正常的数组,汗。。。。
每次拿最右边的值和中间值比较,保证去旋转点可能在的那一半就好。
class Solution {
public:
int findMin(vector<int>& nums) {
int left = 0, right = nums.size() -1;
while( left < right) {
int mid = (left + right) /2;
if(nums[mid] < nums[right]){
right = mid;
}
else {
left = mid + 1;
}
}
return nums[left];
}
};