算法-目录
题目来源:Leetcode 34. 在排序数组中查找元素的第一个和最后一个位置
class Solution(object):
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
if len(nums)==0 or nums[0]>target or nums[-1]<target:
return [-1,-1]
lm=self.searchleft(nums,target)
rm=self.searchright(nums,target)
return [lm,rm]
def searchleft(self, nums, target):
low,high=0,len(nums)-1
while low<=high :
mid=low+(high-low)//2
if nums[mid]>=target:
high=mid-1
else:
low=mid+1
if nums[low]==target:
return low
else:
return -1
def searchright(self, nums, target):
low,high=0,len(nums)-1
while low<=high :
mid=low+(high-low)//2
if nums[mid]<=target:
low=mid+1
else:
high=mid-1
if nums[high]==target:
return high
else:
return -1