Description:
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]
解题思路:
这是一道二分查找和array(列表)的综合应用题,下界用一般的二分查找即可获得。问题在于上界,此时我们可以考虑类似于反向二分查找的方法,mid整除2后加1,条件判断时选择-1,这与普通二分查找反向对应,通过这样的方法可获得上界。简而言之,通过两次二分查找取得下界和上界。
Solution:
class Solution:
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
left = 0;
right = len(nums) - 1;
while left < right:
mid = (left + right) // 2
if nums[mid] < target:
left = mid + 1
else:
right = mid
if left > right:
lower = -1
elif nums[left] != target:
lower = -1
else:
lower = left
left = 0;
right = len(nums) - 1;
while left < right:
mid = (left + right) // 2 + 1
if nums[mid] > target:
right = mid - 1
else:
left = mid
if left > right:
upper = -1
elif nums[right] != target:
upper = -1
else:
upper = right
return [lower,upper]
分析:
时间复杂度:O(logn)
空间复杂度:O(1)
提交结果: