Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7] might become:
[4,5,6,7,0,1,2] if it was rotated 4 times[0,1,2,4,5,6,7] if it was rotated 7 timesGiven the sorted rotated array nums of unique elements, return the minimum element of this array.
You must write an algorithm that runs in O(log n) time.
Input: nums = [3,4,5,1,2]
Output: 1
Explanation: The original array was [1,2,3,4,5] rotated 3 times.
Input: nums = [4,5,6,7,0,1,2]
Output: 0
Explanation: The original array was [0,1,2,4,5,6,7] rotated 4 times.
Input: nums = [11,13,15,17]
Output: 11
Explanation: The original array was [11,13,15,17] and it was rotated 4 times (no rotation effect).
In a rotated sorted array:
nums[mid] > nums[right]: minimum is in right half (rotation point is right)nums[mid] ≤ nums[right]: minimum is in left half or at midKey insight: Compare mid with right endpoint to determine which half contains the minimum.
This is Modified Binary Search with these characteristics:
Initialize: left = 0, right = n - 1
Binary Search:
nums[left] < nums[right]: Array not rotated, return nums[left]mid = left + (right - left) / 2nums[mid] > nums[right]:
left = mid + 1right = midReturn: nums[left] (minimum element)
1class Solution {
2 public int findMin(int[] nums) {
3 int left = 0;
4 int right = nums.length - 1;
5
6 while (left < right) {
7 // If this portion is sorted, leftmost is minimum
8 if (nums[left] < nums[right]) {
9 return nums[left];
10 }
11
12 int mid = left + (right - left) / 2;
13
14 if (nums[mid] > nums[right]) {
15 // Minimum is in right half
16 left = mid + 1;
17 } else {
18 // Minimum is at mid or in left half
19 right = mid;
20 }
21 }
22
23 return nums[left];
24 }
25}
26