Life saving Python Code With All Edge Cases Crystally Clear Explained.


  • -1

    All the code I have read so far this, that are using
    start = mid + 1 to deal with edge case when nums is [2,1] or [3,1].
    It is extremely confusing. Reading those people's code is basically wasting my life.
    and of course, you have used start = mid + 1 to make your code 1% shorter but 1000% less comprehensible.

    class Solution(object):
        def findMin(self, nums):
            low, upper = 0, len(nums)-1
            # case like empty nums or None
            if len(nums) == 0:
                return 0
            # case when length is 1 
            if len(nums) == 1:
                return nums[0]
           # case when length of nums >=2
           # low+1 = upper make sure all the case side length > 2
            while low+1 <= upper: 
                mid = low + (upper-low)/2
               #case [2,3] or [1,3]
                if low+1 == upper:
                    return min(nums[low],nums[upper])
                if nums[low] < nums[upper]:  # case it is already in sorted order 1,2,3
                    return nums[low]
                if nums[mid] > nums[upper]:  # case like [7,8,1,2,3,4,5] ;  in general   nums[low] > nums[mid]  < nums[upper]
                    low = mid
                elif nums[mid] < nums[upper]: #  case like [7,8,1,2,3,4,5] , in general  nums[low] < nums[mid]  >nums[upper]
                    upper = mid    
               # we dont need return because all case has already been considered 
    

Log in to reply
 

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