python二分查找问题set

Posted 一条图图犬

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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]

以上是关于python二分查找问题set的主要内容,如果未能解决你的问题,请参考以下文章

python算法:二分查找

python算法之二分查找

python实现二分查找与冒泡排序

python实现二分查找

Python 算法之二分查找

算法图解(二分查找)