Given a sorted array of integers, 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]
.
For example,
Given [5, 7, 7, 8, 8, 10]
and target value 8,
return [3, 4]
.
题意分析:
本题是在一个递增数组中查找目标值target下标的边界,可以得到两个信息:1.数组会有重复值;2.数组是严格单调递增的。
解答:
本题要求时间复杂度是 O(log n),提示我们可以用二分查找去做(注意不能先用二分查找找到target,然后向两侧寻找边界,这种方法是不符合时间复杂度要求的)。既然是一个范围,那么我们可以查找两次,分别把两个边界找出来。这里我是先查找到左边界,然后将左边界后面的数组作为新的数组查找右边界。这和二分查找的思想一致,但是需要注意迭代的条件是不同的。
AC代码:
class Solution(object):
def searchRange(self, nums, target):
left = 0
right = r_right = len(nums) - 1
# find the left of range
while left < right:
mid = (left + right) / 2
if nums[mid] < target:
left = mid + 1
else:
right = mid
# can't find target
if nums[left] != target:
return [-1, -1]
while right < r_right:
# notice: mid should be close to right
mid = (right + r_right) / 2 + 1
if nums[mid] > target:
r_right = mid - 1
else:
right = mid
return [left, right]