python二分查找问题set

leetcode34 Search for a Range

class Solution:
    def searchRange(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        if not nums:
            return [-1, -1]

        def search(n):
            st = 0
            ed = len(nums) - 1
            while st <= ed:
                mid = (st + ed) // 2
                if nums[mid] == n:
                    if mid-1 >= 0 and nums[mid - 1] == n:
                        mid -= 1
                    return mid
                if nums[mid] < n:
                    st = mid + 1
                else:
                    ed = mid - 1

            return st

        right = left = search(target)
        if left>len(nums)-1:
            return [-1, -1]
        try:
            if nums[left] != target:
                return [-1, -1]
        except:
            pass
        try:
            while left-1 >= 0 and nums[left - 1] == target:
                left -= 1
            while nums[right + 1] == target:
                right += 1
        except:
            pass

        return [left, right]
posted @ 2017-12-11 09:56  一条图图犬  阅读(173)  评论(0编辑  收藏  举报