Easy understanding Java binary search solution


  • -1
    Y
    public int findMin(int[] nums) {
        return binarySearch(nums, 0, nums.length - 1);
    }
    
    private int binarySearch(int[] nums, int start, int end){
        if(start == end) return nums[start];
        else if(start + 1 == end) return nums[start] < nums[end] ? nums[start] : nums[end];
        else{
            int mid = (start + end) / 2;
            if(nums[mid] < nums[mid - 1] && nums[mid] < nums[mid + 1]) return nums[mid];
            else{ 
                int left = binarySearch(nums, start, mid - 1);
                int right = binarySearch(nums, mid + 1, end);
                return left < right? left : right;
            }
            
        }
    }

Log in to reply
 

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