Description: Given an array of integers nums
sorted in ascending order, find the starting and ending position of a given target
value. If target
is not found in the array, return [-1, -1]
.
Follow up: Could you write an algorithm with O(log n)
runtime complexity?
Link: 34. Find First and Last Position of Element in Sorted Array
Examples:
Example 1: Input: nums = [5,7,7,8,8,10], target = 8 Output: [3,4] Example 2: Input: nums = [5,7,7,8,8,10], target = 6 Output: [-1,-1] Example 3: Input: nums = [], target = 0 Output: [-1,-1]
思路: 首先用正常的二分查找流程找到target所在的任意index,如何找不到就返回[-1,-1],如果找到了,当前mid = index所在的区间[l,r]一定包含目标值的start,end,再在这里区间中分别确定start 和 end 的位置。也是利用二分查找。start可能在[l,mid-1]里,end可能在[mid+1,r]里,过一个例子就知道start=sl,end=er.
class Solution(object): def searchRange(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ if not nums: return [-1,-1] n = len(nums) l, r = 0, n-1 while l <= r: mid = int((l+r)/2) if nums[mid] == target: sl = l sr = mid-1 while sl <= sr: sm = int((sl+sr)/2) if nums[sm] == target: sr = sm - 1 else: sl = sm + 1 el = mid+1 er = r while el <= er: em = int((el+er)/2) if nums[em] == target: el = em + 1 else: er = em - 1 return [sl, er] elif target > nums[mid]: l = mid + 1 else: r = mid - 1 return [-1,-1]
日期: 2021-04-10 所有人,所有事都在告诉我,没有人能随随便便成功,要坚持啊!