采用二分查找找出某个数字的下标,二分查找找出下标,class Soluti


class Solution(object):    def searchRange(self, nums, target):        """        :type nums: List[int]        :type target: int        :rtype: List[int]        """        def binary_search(start,end,value):            while end>=start:                mid = (start+end)//2                print(mid)                if nums[mid]>target:                    end = mid-1                elif nums[mid]<target:                    start = mid+1                else:                     if value==-1:                        if mid-1>=start and nums[mid+value] == target:                            end = mid+value                        else:                            return mid                    else:                        if mid+1<=end and nums[mid+value] == target:                            start = mid+value                        else:                            return mid            return -1        a=binary_search(0,len(nums)-1,-1)        b=binary_search(0,len(nums)-1,1)        return [a,b]a = Solution()l = [2,2]print(a.searchRange(l,2))

评论关闭