[leedcode 154] Find Minimum in Rotated Sorted Array II
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 a sorted array 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.
public class Solution { public int findMin(int[] nums) { //注意:当mid等于left并且等于right时,需要使用常规方法进行寻找,其他情况和之前相同 //注意单调递增的处理 if(nums==null||nums.length<=0) return -1; int left=0; int right=nums.length-1; if(nums[left]<nums[right])return nums[left];///// while(left<right-1){ int mid=(left+right)/2; if(nums[mid]==nums[left]&&nums[mid]==nums[right]){ return find(nums,left,right); } if(nums[mid]>=nums[left]){ left=mid; }else right=mid; } return nums[right]; } public int find(int[] nums,int left,int right){ int res=nums[left]; for(int i=left+1;i<=right;i++){ if(res>nums[i]) res=nums[i]; } return res; } }