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) {
if(num.size() == 0) return 0;
int minimum = 0x7fffffff;
// Define the left and right to points to the start and end of the candidates.
int left = 0;
int right = num.size() - 1;
while(left <= right) {
int mid = (left + right) / 2;
// if left to mid is ascending
if(num[left] <= num[mid]) {
minimum = min(minimum, num[left]);
left = mid + 1;
}
else if(num[mid] <= num[right]) { // if mid to right is ascedning
minimum = min(minimum, num[mid]);
right = mid - 1;
}
}
return minimum;
}
};