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.
- 解题思路
二分查找 - 实现代码
/*************************************************************
* @Author : 楚兴
* @Date : 2015/2/8 17:17
* @Status : Accepted
* @Runtime : 10 ms
*************************************************************/
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int findMin(vector<int> &num) {
int begin = 0;
int end = num.size() - 1;
int mid;
while (begin + 1 < end)
{
mid = (begin + end) / 2;
if (num[mid] > num[end])
{
begin = mid;
}
else
{
end = mid;
}
}
return num[begin] < num[end] ? num[begin] : num[end];
}
};
int main()
{
Solution s;
vector<int> nums;
nums.push_back(4);
nums.push_back(5);
nums.push_back(6);
nums.push_back(7);
nums.push_back(1);
nums.push_back(2);
nums.push_back(3);
cout<<s.findMin(nums)<<endl;
system("pause");
}
- 根据官方解答优化后的代码:
/*************************************************************
* @Author : 楚兴
* @Date : 2015/2/8 17:46
* @Status : Accepted
* @Runtime : 7 ms
*************************************************************/
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int findMin(vector<int> &num) {
int begin = 0;
int end = num.size() - 1;
int mid;
while (begin < end)
{
mid = (begin + end) / 2;
if (num[mid] > num[end])
{
begin = mid + 1;
}
else
{
end = mid;
}
}
return num[begin];
}
};