2-Brother Codes to implement I and II -- showing minor difference clearly


  • 1
    L

    Younger brother: this is for no-duplicate case I.

    public int FindMin(int[] nums) {
        int left = 0, right = nums.Length - 1;
        while(left < right){
            int mid = (left + right) >> 1;
            if(nums[mid] > nums[right]) left = mid + 1;
            else if (nums[mid] < nums[right]) right = mid;
        }
        return nums[right];
    }
    

    Elder brother: this is for Duplicate case II.

    public int FindMin(int[] nums) {
        return findMin(nums, 0, nums.Length - 1);
    }
    
    private int findMin(int[] nums, int left, int right){
        while(left < right){
            int mid = (left + right) >> 1;
            if(nums[mid] > nums[right]) left = mid + 1;
            else if (nums[mid] < nums[right]) right = mid;
            else //nums[mid] == nums[right]
                return Math.Min(findMin(nums, left, mid), findMin(nums, mid + 1, right));
        }
        return nums[right];
    }

Log in to reply
 

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