开始之前:从2018/8/27开始刷LeetCode,计划每周刷五题,周末进行总结并发布在csdn上,计划先刷150道题,从简单开始。
week 3-1
要求:
CODE:
class Solution:
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
# 如果要搜索的目标存在与数组中则直接输出
if target in nums:
return nums.index(target)
# 设置index上下限
left = 0
right = len(nums) - 1
while left <= right:
mid = (left + right) // 2
if target < nums[mid]:
right = mid - 1
elif target > nums[mid]:
left = mid + 1
else:
return mid
return left
结果:
备注:其实我一开始挺震惊的,这个竟然比我快,大概是48ms,只是一个简单的for循环,后来想想也有道理。二叉查找的复杂度是O(long2n),最耗时的情况就是target不存在于nums中,而这种情况看来在测试例中相当常见。
class Solution:
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
for i in range(len(nums)):
if target<=nums[i]:
return i
return len(nums)
注意:该题使用二分查找
二分查找的代码应该牢记,这里贴出来供大家参考:
def binarySearch(target, nums):
"""
二分查找的前提是原数组已排序
"""
# 定义索引上限和下限
left = 0
right = len(nums) - 1
while left <= right:
mid = (left + right) // 2
if target < nums[mid]:
right = mid - 1
elif target > nums[mid]:
left = mid + 1
else:
return mid
return left # 当数组中不存在target时会返回其应该排序的位置