2015年10月15日星期四

Leetcode 153 Find Minimum in Rotated Sorted Array

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.
You may assume no duplicate exists in the array.
Solution 1: Binary search, pay attention to termination condition.
 public class Solution {  
   public int findMin(int[] nums) {  
     int n=nums.length;  
     int lo=0, hi=n-1;  
     while (lo<hi) {  
       int mid=lo+(hi-lo)/2;  
       if (nums[mid]>nums[hi]) lo=mid+1;//pay attention mid will not equal to hi until finish  
       else hi=mid;  
     }  
     return nums[lo];  
   }  
 }  

没有评论:

发表评论