在排序数组中查找元素的第一个和最后一个位置
第一版
def searchRange(nums: list[int], target: int) -> list[int]:
res = [-1,-1]
if not nums:
return res
length = len(nums)
if nums[0] == target:
res[0] = 0
if nums[-1] == target:
res[1] = length - 1
for i in range(length):
if i > 0 and nums[i - 1] != target and nums[i] == target:
res[0] = i
if i < length - 1 and nums[i] == target and nums[i + 1] != target:
res[1] = i
break
return res
优化后:
def searchRange(nums: list[int], target: int) -> list[int]:
res = []
length = len(nums)
for i in range(length):
if nums[i] == target:
res.append(i)
if i < length - 1 and nums[i] != nums[i + 1]:
break
return [res[0],res[-1]] if len(res) > 0 else [-1,-1]
看到说用二分查找,不过我还没去试