LeetCode 数组·35:搜索插入位置|python解法
LeetCode 数组·35:搜索插入位置|python解法
1 题目描述
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
2 题目要求
必须使用时间复杂度为 O(log n) 的算法
3 Python解法
import bisect
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
if target in nums:
return nums.index(target)
else:
bisect.insort(nums, target)
return nums.index(target)
bisect库介绍
作用:管理已排序的序列
bisect 模块包含两个主要函数,bisect 和 insort,两个函数都利用二分查找算法来在有序序列中查找或插入元素。
-
用bisect搜索序列中的目标值
bisect(haystack, needle) 在 haystack(干草垛)里搜索needle(针)的位置,该位置满足的条件是,把 needle 插入这个位置之后,haystack 还能保持升序。也就是在说这个函数返回的位置前面的值,都小于或等于 needle 的值。其中 haystack 必须是一个有序的序列。你可以先用 bisect(haystack, needle) 查找needle的位置 index,再用 haystack.insert(index, needle) 来插入新值。 -
用insort 一步到位
在序列中插入needle 原地修改原序列。用insort 来一步到位,并且后者的速度更快一些。bisect.insort(haystack, needle)