Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
1
| (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.
1 2 3 4 5 6 7 8 9
| Example 1:
Input: [3,4,5,1,2] Output: 1
Example 2:
Input: [4,5,6,7,0,1,2] Output: 0
|
Notes
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| - no dups - rotation pivot in not known? - sorted in ascending order - min should be at pivot - peak just before pivot if pivot is not 0
1, 3, 5 --> pivot is at 0 - min is 1 56781234 --> min is 1 min 5
test 6 test 7 test 8 test 1 ---> min is 1 break
|
The following is a O(n)
solution
1 2 3 4 5 6 7 8 9 10 11
| int findMin(vector<int>& nums) { int min = nums[0]; for (int i = 0; i < nums.size(); i++) { if ((i < nums.size() - 1) && nums[i] > nums[i+1]) { min = nums[i+1]; break; } } return min; }
|
There is a O(logn)
solution that uses binary search!