34. 在排序数组中查找元素的第一个和最后一个位置
给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。
如果数组中不存在目标值 target,返回 [-1, -1]。
典型的二分题(因为原数组是升序排列的),时间复杂度O(logn)
先贴个一行代码吧(图个好看,时间复杂度upup)
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
return [nums.index(target),len(nums)-1-nums[::-1].index(target)] if target in nums else [-1,-1]
二分法
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
n = len(nums)
def twosearch(left,right):
if left > right:
return -1
mid = (right+left)>>1
if nums[mid]==target:
return mid
return twosearch(mid+1,right) if nums[mid]<target else twosearch(left,mid-1)
index = twosearch(0,n-1)
l = r = index
if index == -1 :
return [l,r]
while(l>0):
l -= 1
if nums[l] ^ target:
l += 1
break
while(r<n-1):
r += 1
if nums[r] ^ target:
r -= 1
break
return [l,r]