您的位置:首页 > 其它

LeetCode——Find Minimum in Rotated Sorted Array II

2017-10-02 13:36 369 查看

Question

Follow up for "Find Minimum in Rotated Sorted Array":

What if duplicates are allowed?

Would this affect the run-time complexity? How and why?

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.

Solution

抓住数组的特点。

Code

class Solution {
public:
int findMin(vector<int>& nums) {
int size = nums.size();
if (size == 1)
return nums[0];
int low = 0;
int high = size - 1;
while (low < high) {
// 没用递归,所以注意求中间节点的方法
int mid = low + (high - low) / 2;
// 如果更小,那么会比右边的都小
if (nums[mid] < nums[high])
high = mid;
// 如果更大,那最小的肯定在右边
else if (nums[mid] > nums[high])
low = mid + 1;
// 如果相等,不知道最大值在左边还是在右边
else
high--;
}
return nums[low];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: