classSolution(object): defsearchRange(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] >>> s = Solution() >>> s.searchRange([5, 7, 7, 8, 8, 10], 8) [3, 4] >>> s.searchRange([5, 7, 7, 8, 8, 10], 6) [-1, -1] >>> s.searchRange([], 0) [-1, -1] >>> s.searchRange([1], 1) [0, 0] >>> s.searchRange([1, 3], 1) [0, 0] >>> s.searchRange([1, 4], 4) [1, 1] >>> s.searchRange([2, 2], 2) [0, 1] """ start = 0 end = len(nums) if end == 0: return [-1, -1] ex = -1 whileTrue: if end - start == 1: if nums[start] == target: ex = start break mid_ind = (start+end)//2 mid = nums[mid_ind] if mid > target: end = mid_ind elif mid < target: start = mid_ind else: ex = mid_ind break # cannot find target in nums. if ex == -1: return [-1, -1]
start = ex end = ex
# extend to the end. for idx in range(ex+1, len(nums)): if nums[idx] == target: end = idx else: break # extend to the start. for idx in range(ex-1, -1, -1): if nums[idx] == target: start = idx else: break return [start, end]