本文共 1957 字,大约阅读时间需要 6 分钟。
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#include using namespace std;class Solution {public: int findMin(vector &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 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< <
/************************************************************* * @Author : 楚兴 * @Date : 2015/2/8 17:46 * @Status : Accepted * @Runtime : 7 ms*************************************************************/#include#include using namespace std;class Solution {public: int findMin(vector &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]; }};
转载地址:http://tcntx.baihongyu.com/