Problem
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:
1 | |
Example 2:
1 | |
Explanation
-
Check if the array is rotated by comparing first element and last element. If the array is not ratated, then return the first element.
-
We can use binary search to solve this problem. Create a left and right pointer that points to beginning index and end index of the array. Then we can get the middle index element
nums[mid], and compare it with the right elementnums[right]. -
if
nums[mid]is greater thannums[right], then we updateleft = mid + 1.1
2
3
4
5
6
7
8/ mid / / / left/ /right / min -
Else if
nums[mid]is less thannums[right], then we updateright = mid.1
2
3
4
5
6
7
8
9/ / left /right / / /mid / min -
Else
nums[mid]equal tonums[right], that meansleft == rightsince all elements are unique, we break out the while loop and returnnums[left].
Solution
1 | |