[LeetCode] 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.
Thought process:
O(n) solution is trivial, so we aim to solve this problem using binary search. For each middle element we find, we compare it with the last element of the array. There are two cases:
- nums[mid] <= last element: mid is on the part that's been rotated to the right. The minimum element is to the left of mid.
- nums[mid] > last element: mid is on the part that's not rotated. The minimum element is to the right of mid.
Solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | public class Solution { public int findMin(int[] nums) { int start = 0; int end = nums.length - 1; int last = nums[end]; while (start + 1 < end) { int mid = start + (end - start) / 2; if (nums[mid] < last) { end = mid; } else { start = mid; } } if (nums[start] < nums[end]) { return nums[start]; } else { return nums[end]; } } } |
Note that start is not always going to be the minimum element. Think about the case when there're only two numbers.
Time complexity: O(logn).
Comments
Post a Comment