Recursive Solution in Java


  • 0
    G
    public int findMin(int[] nums) {
        return binary(nums, 0, nums.length - 1);
    }
    
    public int binary(int[] nums, int lo, int hi){
        if(lo == hi)
            return nums[lo];
        int mid = (lo + hi) / 2;
            
        if(nums[mid] > nums[hi])
            return binary(nums, mid + 1, hi);
    
        return binary(nums, lo, mid);
    }
    

    Another one with iteration is:

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

Log in to reply
 

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