@author: ZZQ
@software: PyCharm
@file: searchRange.py
@time: 2018/11/12 19:19
要求:给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。
你的算法时间复杂度必须是 O(log n) 级别。
如果数组中不存在目标值,返回 [-1, -1]。
示例 1:
输入: nums = [5,7,7,8,8,10], target = 8
输出: [3,4]
示例 2:
输入: nums = [5,7,7,8,8,10], target = 6
输出: [-1,-1]
思路:1. 二分查找,先找到该元素的位置,然后向前向后搜索其起止位置(好像会到O(n))
2. 分两次搜索,二分查找,先找到起始位置,再找到停止位置。
class Solution():
def __init__(self):
pass
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
nums_len = len(nums)
start_index = -1
end_index = -1
if nums_len == 0:
return [start_index, end_index]
elif nums_len == 1:
if nums[0] == target:
return [0, 0]
else:
return [start_index, end_index]
else:
left = 0
right = nums_len-1
while left <= right:
middle = (left + right) / 2
if nums[middle] == target:
start_index = middle
while nums[middle] == target:
middle += 1
if middle == nums_len:
end_index = middle - 1
break
if end_index == -1:
end_index = middle - 1
while nums[start_index-1] == target:
start_index -= 1
if start_index < 0:
start_index += 1
break
return [start_index, end_index]
elif nums[middle] < target:
left = middle + 1
else:
right = middle - 1
return [start_index, end_index]
def searchRange2(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
nums_len = len(nums)
start_index = -1
end_index = -1
if nums_len == 0:
return [start_index, end_index]
elif nums_len == 1:
if nums[0] == target:
return [0, 0]
else:
return [start_index, end_index]
else:
left = 0
right = nums_len-1
min = nums_len-1
max = 0
while left <= right:
middle = (left + right) / 2
if nums[middle] == target:
if middle < min:
min = middle
if middle > max:
max = middle
right -= 1
elif nums[middle] < target:
left = middle + 1
else:
right = middle - 1
left = 0
right = nums_len - 1
while left <= right:
middle = (left + right) / 2
if nums[middle] == target:
if middle < min:
min = middle
if middle > max:
max = middle
left += 1
elif nums[middle] < target:
left = middle + 1
else:
right = middle - 1
if min > max:
return [-1, -1]
else:
return [min, max]