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.
Example 1:
Input: [3,4,5,1,2]
Output: 1
Example 2:
Input: [4,5,6,7,0,1,2]
Output: 0
思路:
1 暴力搜索,遍历一遍数组找出最小值,时间代价O(n);2 二分查找,详细参考:here。
1 暴力搜索
int findMin(vector<int>& nums) {
int res = INT_MAX;
for (auto i : nums) {
res = min(res, i);
}
return res;
}
2 二分查找
int findMin2(vector<int>& nums) {
if (nums.size() == 1) return nums[0];
if (nums.size() == 2) return min(nums[0], nums[1]);
decltype(nums.size()) left = 0;
decltype(nums.size()) right = nums.size()-1;
decltype(nums.size()) mid = (left + right) / 2;
while (right - left >= 2) {
if (nums[mid] < nums[mid + 1] && nums[mid] < nums[mid - 1]) return nums[mid];
if (nums[left] < nums[mid] && nums[left] > nums[right]) {
left = mid;
mid = (left + right) / 2;
}
else {
right = mid;
mid = (left + right) / 2;
}
}
return min(nums[left], nums[right]);
}