leetcode 153. Find Minimum in Rotated Sorted Array
Suppose an array sorted in ascending order 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.
思路:这题目炸一看O(n)扫一遍不就行了吗,但作为程序员的我们要写出最优的代码。分析一下可以知道数列的走势是这样的。
那么显然二分一下就可以了,每次比较中值和右边的值。见代码。
class Solution {
public:
int findMin(vector<int>& nums) {
int r = nums.size() - 1;
int l = 0;
while (l < r) {
int mid = (r - l)/2 + l;
if (nums[mid] < nums[r]) r = mid;
else l = mid + 1;
}
return nums[l];
}
};
原文地址:http://www.cnblogs.com/pk28/
与有肝胆人共事,从无字句处读书。
欢迎关注公众号:
欢迎关注公众号: