Given an array of integers nums
sorted in ascending order, find the starting and ending position of a given target
value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1]
.
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]
解题思路:
因为题目要求的的时间复杂度为O(log n)所以这道题肯定是需要二分法来查找的。但这个二分法查找有一点不一样。
要找到target的first position 和last position,只需要找到排序数组中的第一个大于等于target的数的位置(lowerbound),和第一个大于targe的数的位置(upperbound),那么最后的target的fist position和last postion为(lowerbound,upperbound),然后再处理一下其他特殊情况即可。
代码如下:
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
if not nums:
return [-1,-1]
if len(nums) == 1:
return [0,0] if nums[0] == target else [-1,-1]
low = self.findLowerBound(nums,target)
upper = self.findUpperBound(nums,target)
return[low,upper]
def findLowerBound(self, nums: List[int], target: int) -> int:
# 此时找出的low是第一个大于或等于target的数
start = 0
end = len(nums)-1
# find lowerbound
while start < end:
mid = (start+end)//2
if nums[mid] >= target:
end = mid
else:
start = mid +1
#print(start)
if nums[start] == target:
return start
else:
return -1
def findUpperBound(self, nums: List[int], target: int) -> int:
# find upperbound
#此时upper找出的数是最后一个大于或等于target的(对于数组中的数全是target时,跳出条件也是start == end)
start = 0
end = len(nums)-1
while start < end:
mid = (start+end)//2
if nums[mid] > target:
end = mid
else:
start = mid +1
if nums[end] == target:
return end
elif nums[end-1] == target:
return end-1
else:
return -1