题目链接 | 35. 搜索插入位置 |
---|---|
思路 | 二分查找 |
题解链接 | 二分查找总是写不对?一个视频讲透!(Python/Java/C++/C/Go/JS/Rust) |
关键点 | 排序数组 => 二分查找 |
时间复杂度 | \(O(\log n)\) |
空间复杂度 | \(O(1)\) |
代码实现(开区间写法):
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
left, right = -1, len(nums)
while left + 1 < right:
mid = (left+right) // 2
if nums[mid] < target:
left = mid
else:
right = mid
return right
Python-库函数
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
return bisect_left(nums, target)