154. Find Minimum in Rotated Sorted Array II
154. Find Minimum in Rotated Sorted Array II
难度:Hard
内容
题目链接:https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii
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.
The array may contain duplicates.
Example 1:
Input: [1,3,5]
Output: 1
Example 2:
Input: [2,2,2,0,1]
Output: 0
Note:
- This is a follow up problem to Find Minimum in Rotated Sorted Array.
- Would allow duplicates affect the run-time complexity? How and why?
思路
这题竟然是hard,好尴尬。最简单时间复杂度为O(n)的方法,我把前一题的代码一行不动的挪过来,Accepted。 二分查找法,时间复杂度为O(log(n))。
代码
O(n),和前一题代码一样
class Solution {
public:
int findMin(vector<int>& nums) {
int res_idx = 0;
for (int i = 1; i < nums.size(); ++i)
if (nums[i] < nums[i-1]) {
res_idx = i;
break;
}
return nums[res_idx];
}
};
二分法实现
class Solution {
public:
int findMin(vector<int>& nums) {
int left = 0, right = nums.size() - 1;
while (left < right && nums[left] >= nums[right]) {
int mid = left + (right - left) / 2;
if (nums[mid] == nums[left]) {
++left;
} else if (nums[mid] < nums[left]) {
right = mid;
} else {
left = mid + 1;
}
}
return nums[left];
}
};
迭代器二分查找的实现
class Solution {
public:
int findMin(vector<int>& nums) {
auto left = nums.begin();
auto right = std::prev(nums.end());
while (*left >= *right && left < right) {
auto gap = (right - left) >> 1;
if (*next(left, gap) == *left)
advance(left, 1);
else if (*next(left, gap) < *left)
advance(right, -gap);
else
advance(left, gap + 1);
}
return *left;
};
来源:https://github.com/xiaqunfeng/leetcode