Is there any rules when add '==' in the while condition checking?


  • 0
    C

    When doing binary search, sometimes we can add "==" condition checking in the "while" checking, sometimes we can complete it in another way. For example, (I) is my implementation and (II) comes from StefanPochmann, which one should be the common rule?

    # I 
    def findMin1(self, nums):
        l, r = 0, len(nums)-1
        while l <= r:
            if nums[l] <= nums[r]:
                return nums[l]
            mid = l + (r-l)//2
            if nums[l] <= nums[mid]:
                if nums[mid] < nums[r]:
                    return nums[l]
                else:
                    l = mid + 1
            else:
                r = mid 
    # II           
    def findMin(self, nums):
        l, r = 0, len(nums)-1
        while l < r:
            mid = l + (r-l)//2
            if nums[mid] > nums[r]:
                l = mid + 1
            else:
                r = mid
        return nums[l]
    

Log in to reply
 

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