二分定位,再前后遍历
class Solution:
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
if nums==[]:
return [-1,-1]
p = 0
q = len(nums)
while p < q:
mid = (p+q)//2
if nums[mid] == target:
break
elif nums[mid] > target:
q = mid
else:
p = mid + 1
if p>=q:
return [-1,-1]
l = mid
r = mid
while l>=0 and nums[l] == target:
l-=1
while r<len(nums) and nums[r] == target:
r+=1
return [l+1,r-1]

本文介绍了一种使用二分查找定位目标元素,并在有序数组中搜索目标元素出现范围的算法实现。通过定义一个Solution类,该类包含searchRange方法,接受一个整数列表和目标整数作为输入,返回目标元素的起始和结束位置。
367

被折叠的 条评论
为什么被折叠?



