Easy java solution with comments


  • 0
    D

    public class Solution {
    public int findMin(int[] nums) {

        //base case: if array has only 1 element , return it
        if(nums.length==1)
            return nums[0];
            
        
        //General case: if more than 1 element is present
        int low=0;
        int high=nums.length-1;
        int min=Integer.MAX_VALUE;
        
        while(low<=high)
        {
            int mid=(low+high)/2;
            
            //Case 1: if array is already sorted from left to right
            if(nums[low]<=nums[mid] && nums[mid]<=nums[high])
            {
                if(nums[low]<min)
                {
                    min=nums[low];
                }
                break;
            }
            //Case 2:if mid is smaller than bothe the bounds
            else if(nums[mid]<=nums[low] && nums[mid]<=nums[high])
            {
                if(nums[mid]<min)
                    min=nums[mid];
                    
                high=mid-1;
            }
            //Case 3:if mid is greater than high
            else if(nums[mid]>nums[high])
            {
                low=mid+1;
            }
            
        }
        
        return min;
        
        
        
        
    }
    

    }


Log in to reply
 

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