题目 https://oj.leetcode.com/problems/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.
思路:二分的找,一半是有序的,一半可能是有序的,可能是乱序的,也就是这个问题的子问题。
即这个问题是a,a = b + a/2, b是一个有序的序列,取b第一个元素 和 a/2 最小的元素 的较小值即可。
代码:
class Solution {
public:
int findMin(vector<int> &num) {
if(num.size()==1)
return num[0];
else if(num.size()==2)
return min(num[0], num[1]);
int mid = num.size() / 2;
if(num[0] < num[mid]) {
vector<int> subvec(num.begin()+mid+1, num.end());
return min(findMin(subvec), num[0]);
} else {
vector<int> subvec(num.begin(), num.begin()+mid+1);
return min(num[mid+1], findMin(subvec));
}
}
};