题解 | #在升序数组中查找元素的位置#
在升序数组中查找元素的位置
http://www.nowcoder.com/practice/f2628d9f7b7d4568aebaae6556aacfe0
二分法找左右边界,引入 bisect 模块,bisect_left 求出左边界 l(表示有几个值 < target), bisect_right 求出右边界 r(表示有几个值 <= target), 结果中是该值左侧和右侧的索引, 返回 [l, r - 1]
import bisect
class Solution:
def searchRange(self , nums: List[int], target: int) -> List[int]:
# write code here
if target not in nums: return [-1, -1]
l, r = bisect.bisect_left(nums, target), bisect.bisect_right(nums, target) - 1
return [l, r]
查看18道真题和解析