Leetcode_34. Search for a Range
2018-03-27 10:39
344 查看
Given an array of integers 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
Given
return
# 这题陷阱贼多。
# 解题思路:
两个反方向的binary search确定range. 但是要格外小心,只有一个element的list和target not in list的情况。比如【1】,1
应该返回[0,0].
以下代码:class Solution(object):
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
if not nums:
return -1,-1
left,right=-1,-1
start,end=0,len(nums)-1
while(start<end):
mid=start+(end-start)//2
if nums[mid]<target:
start=mid+1
else:
end=mid
left=start
start,end=left,len(nums)-1
while(start<end):
mid=(end+start)//2+1
if nums[mid]>target:
end=mid-1
else:
start=mid
if nums[start]!=target:
return -1,-1
right=end
return left,right
[-1, -1].For example,
Given
[5, 7, 7, 8, 8, 10]and target value 8,
return
[3, 4].
# 这题陷阱贼多。
# 解题思路:
两个反方向的binary search确定range. 但是要格外小心,只有一个element的list和target not in list的情况。比如【1】,1
应该返回[0,0].
以下代码:class Solution(object):
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
if not nums:
return -1,-1
left,right=-1,-1
start,end=0,len(nums)-1
while(start<end):
mid=start+(end-start)//2
if nums[mid]<target:
start=mid+1
else:
end=mid
left=start
start,end=left,len(nums)-1
while(start<end):
mid=(end+start)//2+1
if nums[mid]>target:
end=mid-1
else:
start=mid
if nums[start]!=target:
return -1,-1
right=end
return left,right
相关文章推荐
- LeetCode-34. Search for a Range
- LeetCode 34. Search for a Range
- LeetCode 34 Search for a Range
- leetcode 34 Search for a Range(二分法)
- Leetcode34. Search for a Range
- LeetCode 34.Search for a Range
- 【LeetCode 34】Search for a Range
- leetcode34. Search for a Range
- LeetCode 34: Search for a Range
- [leetcode 34] Search for a Range
- Leetcode-34. Search for a Range
- leetcode--34--Search for a Range
- [leetcode-34]Search for a Range(C)
- python写算法题:leetcode: Add to List 34. Search for a Range
- 【LeetCode】34. Search for a Range
- LeetCode 34. Search for a Range
- leetcode(34) - Search for a Range
- [leetcode 34] Search for a Range
- leetcode 34. Search for a Range
- [leetcode] 【查找】 34. Search for a Range