题目描述:
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
请必须使用时间复杂度为 O(log n) 的算法。
示例1:
示例2:
示例3:
示例4:
示例5:
先完成时间复杂度为O(n)的算法,即从头到尾查找:
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if target in nums:
return nums.index(target)
else:
for i in range(len(nums)):
if i == 0 and nums[i] > target:
return 0
elif i < len(nums) - 1 and nums[i] < target < nums[i + 1]:
return i+1
elif i == len(nums) -1 and nums[i] < target:
return i+1
很明显,时间复杂度不符合题目的要求,再改为O(logn)的算法,即将从头到尾查找改为二分查找。
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
l = len(nums)
left = 0
right = l-1
while(left <= right):
mid = (left + right) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
left = mid + 1
elif nums[mid] > target:
right = mid - 1
return left
熟悉二分查找框架。