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:
1Example 2:
Input:
[4,5,6,7,0,1,2]
Output:
0Analysis
Search in Rotated Sorted Array变形。基本思想还是利用Binary Search,但是在如何移动左右boundary时要相应调整。
不论用Template #1,#2,#3,本质都是在寻找一个非单调递增区间,这个区间就包含了最小值。
Source: https://leetcode.com/articles/find-minimum-in-rotated-sorted-array/
If the array is not rotated and the array is in ascending order, then last element > first element.
Inflection Point
All the elements to the left of inflection point > first element of the array.
All the elements to the right of inflection point < first element of the array.
Template #1 Algorithm
Find the
midelement of the array.If
mid element > first element of arraythis means that we need to look for the inflection point on the right ofmid.If
mid element < first element of arraythis that we need to look for the inflection point on the left ofmid.We stop our search when we find the inflection point, when either of the two conditions is satisfied:
nums[mid] > nums[mid + 1]Hence, mid+1 is the smallest.nums[mid - 1] > nums[mid]Hence, mid is the smallest.
Solution
Using Template #1
Using BS Template #3
Using Template #2
Reference
https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/solution/
Last updated
Was this helpful?