问题:34. Search for a Range
题目描述:https://leetcode.com/problems/search-for-a-range/description/
大致意思说,在有序数组中找到target值的索引上下界,例如序列[5,7,7,8,8,10]且target=8,则返回[3,4]。如果不存在则返回[-1,-1]。
使用Python的bisect实现二分查找:
import bisect
class Solution(object):
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
length=len(nums)
if length==0:
return [-1,-1]
i=bisect.bisect_left(nums,target)
if i!=length:
if nums[i]==target:
j=bisect.bisect_right(nums,target)
return [i,j-1]
else:
return [-1,-1]
其中,bisect_left(seq,val)函数返回有序序列seq中小于等于val值的索引下界,而bisect_right(seq,val)则返回seq中大于val值的索引下界。利用该函数可以快速实现二分查找:
import bisect
def bisearch(nums,target):
i=bisect.bisect_left(nums,target)
if i<len(nums) and nums[i]==target:
return i
return -1
la=[1,2,3,4,4,4,4]
print(bisearch(la,4)) # 3