Java binary search


  • 0
    R

    Think about the situations that will happened for the rotation.
    eg.
    1,2,3,4,5,6,0
    3,4,5,6,0,1,2
    4,5,6,0,1,2,3

    public class Solution {
        public int findMin(int[] nums) {
              if (nums == null || nums.length == 0) {
                return 0;
            }
            if (nums.length == 1) {
                return nums[0];
            }
            int lo=0;
            int hi=nums.length-1;
            while(lo<hi){
                int mid=(lo+hi)/2;
                if(mid>0&&nums[mid]<nums[mid-1]) return nums[mid];
                else{
                    if(nums[mid]>nums[mid+1]) lo=mid+1;
                    else{
                        if(nums[mid]>nums[nums.length-1]) lo=mid+1;
                        else hi=mid-1;
                    }
                }
            }
            return nums[lo];
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.