Wednesday, November 18, 2015

leetcode] Find Minimum in Sorted Array

binary search里面总有些off 1 error 不知道怎么破

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
public class Solution{
 public int findMin(int[] nums){
  int left = 0;
  int right = nums.length-1;
  //int min = 
  while (left < right){
   int mid = (left+right)/2;
   if (nums[mid] < nums[left]){
    right = mid;
   }else if (nums[mid] > nums[right]){
    left = mid+1;
   }else{
    return nums[left];
   }
  }

  return nums[left];                                       
 }
}

No comments:

Post a Comment