给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。
如果数组中不存在目标值 target,返回 [-1, -1]。
进阶:
你可以设计并实现时间复杂度为 O(log n) 的算法解决此问题吗?
示例 1:
输入:nums = [5,7,7,8,8,10], target = 8
输出:[3,4]
示例 2:
输入:nums = [5,7,7,8,8,10], target = 6
输出:[-1,-1]
示例 3:
输入:nums = [], target = 0
输出:[-1,-1]
提示:
- 0 <= nums.length <= 10^5
- -10^9 <= nums[i] <= 10^9
- nums 是一个非递减数组
- -10^9 <= target <= 10^9
Python 解答:
1.暴力
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
begin, end = -1, -1
for i in range(len(nums)):
if nums[i] == target:
if begin == -1:
begin = i
end = i
return [begin, end]
2.二分
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
def helper(nums, target, value):
l, r = 0, len(nums)-1
if not nums:
return -1
while l <= r:
mid = (l+r)//2
if nums[mid] < target:
l = mid+1
elif nums[mid] > target:
r = mid-1
else:
if value:
l = mid+1
else:
r = mid-1
if value:
if 0 <= r < len(nums) and nums[r] == target:
return r
else: return -1
else:
if len(nums) > l >= 0 and nums[l] == target:
return l
else: return -1
begin = helper(nums, target, 0)
if begin == -1:
return [-1, -1]
else:
end = helper(nums, target, 1)
return [begin, end]
留言