Leetcode-34-Search for a Range-(Medium)

时间:2022-03-23 08:28:32

这道题借助二分查找算法来查找目标值的index

然后向前和向后分别搜索起始边界

注意开始排除异常值优化速度

#!/usr/local/bin/python3
# -*- coding: utf-8 -*-
__author__ = 'author' class Solution(object):
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
length = len(nums)
if len(nums) == 0 or nums[0] > target or nums[length - 1] < target:
return [-1, -1]
index = self.binary_search(nums, 0, length - 1, target)
if index == -1:
return [-1, -1]
else:
start = index
end = index
for i in range(index - 1, -1, -1):
if nums[i] == target:
start = i
else:
break
for i in range(index + 1, length):
if nums[i] == target:
end = i
else:
break
return [start, end] #二分查找算法
def binary_search(self, nums, start, end, targrt):
if start > end:
return -1
mid = start + (end - start)//2
if nums[mid] > targrt:
return self.binary_search(nums, start, mid - 1, targrt)
elif nums[mid] < targrt:
return self.binary_search(nums, mid + 1, end, targrt)
else:
return mid

另外的一种思路是寻找 target-1 和 target+1的所在位置的索引,这两个值可能不存在,那么需要相应的修改二分查找算法