Search for a Range

这一题是二分查找的变体,先通过二分查找找到一个坐标,然后左右扩展

class Solution(object):
    def searchRange(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        if len(nums) == 0:
            return [-1,-1]
        if len(nums) == 1:
            if nums[0] == target:
                return [0,0]
            else:
                return [-1,-1]
        index = self.binary_search(nums,target)
        if index == -1:
            return [-1,-1]
        else:
            l = index; q = index
            while l > 0 and nums[l - 1] == nums[index]:
                l -= 1
            while q < len(nums) -1 and nums[q + 1] == nums[index]:
                q += 1
            return[l,q]
    def binary_search(self, nums, target):
        left = 0
        right = len(nums) - 1
        while left <= right:
            middle = (left + right) / 2
            if target == nums[middle]:
                return middle
            elif target < nums[middle]:
                right = middle - 1
            else:
                left = middle + 1
        return -1
    
        ```

你可能感兴趣的:(Search for a Range)