154. 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:

代码

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)
else if (*next(left, gap) < *left)