leetcode: 34. Search for a Range

来源:互联网 发布:淘宝分销什么意思 编辑:程序博客网 时间:2024/05/21 19:28

Q

Given an array of integers sorted in ascending order, find the starting and ending position of a given target value.Your algorithm's runtime complexity must be in the order of O(log n).If the target is not found in the array, return [-1, -1].

Example

Given [5, 7, 7, 8, 8, 10] and target value 8,return [3, 4].

AC

class Solution(object):    def searchRange(self, nums, target):        """        :type nums: List[int]        :type target: int        :rtype: List[int]        """        import bisect        l, r = bisect.bisect_left(nums, target), bisect.bisect_right(nums, target)        l = -1 if l >= len(nums) or nums[l] != target else l        r = -1 if r == 0 or nums[r - 1] != target else r - 1        return [l, r]if __name__ == "__main__":    assert Solution().searchRange([2, 2], 3) == [-1, -1]    assert Solution().searchRange([5, 7, 7, 8, 8, 10], 8) == [3, 4]


原创粉丝点击