Recursive solution in Java using binary search


  • 0
    S
    public class Solution {
        public int findMin(int[] nums) {
        
        if (nums.length == 0) return -1;
        if ( nums.length == 1) return nums[0];
        
        int ind = bsearch(nums,0,nums.length - 1);
        
        if (ind != -1) return nums[ind];
        return -1;
        
    }
    
    public int bsearch(int[] nums, int low, int high)
    
    {
        
        int mid = low + (high-low)/2;
    
        if (mid>0 && nums[mid] < nums[mid-1]) return mid;
        if (low>high) return low;
        
        if (nums[mid] >= nums[low] && nums[mid] > nums[high])
        {
            return bsearch(nums,mid+1, high);
        }
        else
        {
            return bsearch(nums,low,mid-1);
        }
    
    }
    }

Log in to reply
 

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