2015年10月15日星期四

Leetcode 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.
Solution 1: added corner case to deal with if nums[mid]==nums[hi], we can not reduce by half but only one. Also pay attention, it maybe not rotate any more by operation of lo++, in this case we simply return nums[lo].
 public class Solution {  
   public int findMin(int[] nums) {  
     int n=nums.length;  
     int lo=0, hi=n-1;  
     while (lo<hi) {  
       if (nums[lo]<nums[hi]) return nums[lo];//not rotated anymore  
       int mid=lo+(hi-lo)/2;  
       if (nums[mid]<nums[hi]) hi=mid;  
       else if (nums[mid]>nums[hi]) lo=mid+1;  
       else lo++;  
     }  
     return nums[lo];  
   }  
 }  

没有评论:

发表评论