153. Find Minimum in Rotated Sorted Array
Posted yaoyudadudu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.
Example 1:
Input: [3,4,5,1,2] Output: 1
Example 2:
Input: [4,5,6,7,0,1,2] Output: 0
解题思路:
使用二分搜索来解答这道题,和81. Search in Rotated Sorted Array II以及33. Search in rotated sorted array类似
先观察一下短数组所有可能的rotate:
0 1 2 3 4 5 6
6 0 1 2 3 4 5
5 6 0 1 2 3 4
4 5 6 0 1 2 3
3 4 5 6 0 1 2
2 3 4 5 6 0 1
1 2 3 4 5 6 0
若nums[mid] < nums[right]: 则说明右半部分是有序的此时最小值也可能是nums[mid]
若nums[mid] > nums[left]:则说明左半部分是有序的
我们就到另一半部分去找。
若出现left和mid重合的情况,此时会陷入死循环,我们应该跳出循环然后判断nums[mid] 和 nums[right]谁最小
例:3 4 5 1 2
最后left和mid为5的下标,right为1的下表
代码:
class Solution { public: int findMin(vector<int>& nums) { int left = 0; int right = nums.size()-1; int mid; while(left < right){ mid = left + (right-left)/2; if(left == mid) break; if(nums[mid] < nums[right]){ right = mid; }else if(nums[mid] > nums[right]){ left = mid; } } return min(nums[mid],nums[right]); } };
以上是关于153. Find Minimum in Rotated Sorted Array的主要内容,如果未能解决你的问题,请参考以下文章
153. Find Minimum in Rotated Sorted Array
#Leetcode# 153. Find Minimum in Rotated Sorted Array
153. Find Minimum in Rotated Sorted Array
153. Find Minimum in Rotated Sorted Array