Python binary search concise code

  • 0

    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 =, target-0.5)
        r=, target+0.5)
        if l == r:
            return [-1, -1]
            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
                r = mid
        return l

Log in to reply

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