Description
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.
The array may contain duplicates.
Note:
This is a follow up problem to .
Would allow duplicates affect the run-time complexity? How and why?
Constraints
Approach
Links
Examples
Input: [1, 3, 5]
Output: 1
Input: [2, 2, 2, 0, 1]
Output: 0
Solutions
/**
* Time complexity : O(N)
* Space complexity : O(1)
*/
class Solution {
public int findMin(int[] nums) {
if(nums == null || nums.length == 0) return 0;
int n = nums.length;
int i = 1;
while(i < n && nums[i-1] <= nums[i]) {
i++;
}
if(i >= n) return nums[0];
return nums[i];
}
}
/**
* Time complexity : O(logN)
* Space complexity : O(1)
*/
class Solution {
public int findMin(int[] nums) {
if(nums == null || nums.length == 0) return 0;
int left = 0, right = nums.length-1;
while(left <= right) {
while(left != right && nums[left] == nums[right]) {
left++;
}
if(nums[left] <= nums[right]) {
return nums[left];
}
int mid = (left+right)/2;
if(nums[mid] >= nums[left]) {
left = mid+1;
} else {
right = mid;
}
}
return -1;
}
}
Follow up