Python binary search concise code


  • 0
    J

    instead of using target, using target-0.5 and target+0.5 as new target to find the low and up boundaries

    class Solution(object):
    def searchRange(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        l = self.search(nums, target-0.5)
        r= self.search(nums, target+0.5)
        if l == r:
            return [-1, -1]
        else:
            return [l, r-1]
    def search(self, nums, target):
        l, r = 0, len(nums)
        while l < r:
            mid = (l+r)/2
            if nums[mid] < target:
                l = mid+1
            else:
                r = mid
        return l

Log in to reply
 

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