Follow up for "Find Minimum in Rotated Sorted Array":
What if duplicates are allowed?Would this affect the run-time complexity? How and why?
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.
与Find Minimum in Rotated Sorted Array类似,可以和nums[left]比,也可以和nums[right]比,代码如下:
1 public class Solution { 2 public int findMin(int[] nums) { 3 if(nums==null||nums.length==0) return -1; 4 int low = 0; 5 int high = nums.length-1; 6 while(low < high) { 7 int mid = low + (high - low) / 2; 8 if(nums[low] < nums[high]) return nums[low]; 9 else if(nums[low] < nums[mid]) low = mid + 1; 10 else if(nums[low] > nums[mid]) high = mid; 11 else low++; 12 } 13 return nums[low]; 14 } 15 } 16 // the run time complexity could be two cases. the average case could be logn, the worst case could be O(n), the space complexity could be O(1);
public class Solution {
public int findMin(int[] nums) {
int left= 0;
int right = nums.length-1;
while(left<right){
int mid = left+(right-left)/2;
if(nums[mid]<nums[right]){
right = mid;
}else if(nums[mid]>nums[right]){
left = mid+1;
}else{
right--;
}
}
return nums[left];
}
}