题目内容:
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.
Subscribe to see which companies asked this question
思路:
使用二分查找的变体。使用start和end两个index分别记录前后两个序列的最大值和最小值。那么end指向的那个数字就是整个序列的最小值。结束条件为start+1=end。
代码:
递归实现:
class Solution {
public:
int findMin(vector<int>& nums) {
if(nums.size() == 1)
return nums[0];
return findMin(nums, 0, nums.size()-1);
}
// use start to point to the former part
// use end to point to the later part
// when start is next to end, end is the min number
int findMin(vector<int> &nums, int start, int end) {
if(nums[start] < nums[end])
return nums[start];
if(start + 1 == end)
return nums[end];
int mid((start+end)/2);
if(nums[mid] > nums[start])
return findMin(nums, mid, end);
else
return findMin(nums, start, mid);
}
};
迭代实现:
class Solution {
public:
int findMin(vector<int>& nums) {
if(nums.size() == 1)
return nums[0];
return findMin(nums, 0, nums.size()-1);
}
// use start to point to the former part
// use end to point to the later part
// when start is next to end, end is the min number
int findMin(vector<int> &nums, int start, int end) {
if(nums[start] < nums[end])
return nums[start];
while(start + 1 < end) {
int mid((start+end) >> 1);
if(nums[mid] > nums[start])
start = mid;
else
end = mid;
}
return nums[end];
}
};