7-Line O(LogN) Solution


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

  • 0
    D

    why return nums[right] rather than nums[left]?


  • 0
    L

    Hi Daisy, it's because right is assigned "right = mid;" while left is "left = mid + 1;", so right is always at the minimum number at time of each looping. The difference of "+1/-1" plays key role in divide and conquer.


  • 0
    D

    Thanks lestrois!


  • 0
    C

    I think both nums[right] and nums[left] should be OK in this case, because when breaking the while loop, "left" should be equal to "right".


Log in to reply
 

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