题目描述
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].
例子
Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]
Input: nums = [1], target = 1
Output: [0,0]
Input: nums = [1,3], target = 3
Output: [1,1]
题目含义是指
- 存在两个及两个以上的数等于
target
,那么返回第一个和第最后一个的索引[first_index,last_index]
. - 只有一个数等于
target
,那返回时返回这个索引两次[index,index]
. - 不存在等于
target
的元素,则返回[-1,-1]
2019-06-10 linear search
for i in range(len(nums)):
if nums[i]==target:
left = i
break
else: #如果找不到这样的值,则直接返回`[-1,-1]`
return [-1,-1]
for j in range(len(nums)-1,-1,-1):
if nums[j] == target:
right = j
break
print([left,right])
return [left,right]
Runtime: 68 ms, faster than 75.70% of Python online submissions for Find First and Last Position of Element in Sorted Array.
Memory Usage: 13.4 MB, less than 5.09% of Python online submissions for Find First and Last Position of Element in Sorted Array.
binary search
def find_right_index(nums,left,right,target):
while(left<=right):
mid = (left+right)//2
if nums[mid]>target:
right = mid - 1
else:
left = mid + 1
return right
def find_left_index(nums,left,right,target):
while(left<=right):
mid = (left+right)//2
if nums[mid]<target:
left = mid + 1
else:
right = mid - 1
# print(left)
return left
res = [-1,-1]
left, right = 0, len(nums) - 1
rightmost = find_right_index(nums, left, right, target)
if (rightmost<0 or nums[rightmost]!=target):
#print(res)
return res
res[0] = find_left_index(nums,left,right,target)
res[1] = rightmost
#print(res)
return res
结果分析
Runtime: 64 ms, faster than 79.51% of Python online submissions for Find First and Last Position of Element in Sorted Array.
Memory Usage: 13.1 MB, less than 38.73% of Python online submissions for Find First and Last Position of Element in Sorted Array.