码迷,mamicode.com
首页 > 编程语言 > 详细

python二分查找问题set

时间:2017-12-11 11:23:00      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:problems   pass   type   ble   target   .com   gpo   blog   pos   

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]

python二分查找问题set

标签:problems   pass   type   ble   target   .com   gpo   blog   pos   

原文地址:http://www.cnblogs.com/theodoric008/p/8021702.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!