class Solution(object):
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
def findlow(nums,target,low,high):
while low <= high:
mid = low + (high-low)//2
if nums[mid] == target and (mid == 0 or nums[mid-1] < nums[mid]):
return mid
if nums[mid] >= target:
high = mid-1
else:
low = mid+1
if low > high:
return -1
def findhigh(nums,target,low,high):
while low <= high:
mid = low + (high-low)//2
if nums[mid] == target and (mid == len(nums)-1 or nums[mid+1] > nums[mid]):
return mid
if nums[mid] > target:
high = mid-1
else:
low = mid+1
if low > high:
return -1
ans = []
low = findlow(nums,target,0,len(nums)-1)
high = findhigh(nums,target,0,len(nums)-1)
ans.append(low)
ans.append(high)
return ans
学习笔记 | 在排序数组中查找元素的第一个和最后一个位置
最新推荐文章于 2020-07-28 10:33:40 发布