Leetcode 35: 搜索插入位置(python)
注:本人文章中有时有来自于各大佬的经验总结,仅供自身复习及学习,并无商业用途,若有时忘记标注作者及出处还请提醒,敬请见谅。
我的解法
我的思路就是,首先判断target在不在nums数组中,如果在的话,直接使用index函数返回其索引,否则遍历数组,找到数组中第一个比target大的数的索引并返回。
代码如下:
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
if target not in nums:
for i,val in enumerate(nums):
if target < val:
return i if i > 0 else 0
return len(nums)
else:
return nums.index(target)
大佬思路
在题解评论区发现一个特别简洁的思路,只是复杂度是O(n),但是这个思路还是非常妙的!
以下内容来源于leetcode的in3tantc:
解题思路
由题意,无论target在不在有序列表中,只需要得到比target小的数的个数即为target索引。
代码
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
return len([ x for x in nums if x < target ])
作者:in3tantc
链接:https://leetcode-cn.com/problems/search-insert-position/solution/python3-bu-yong-er-fen-fa-he-xiang-guan-edp1o/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
二分搜索
忽然发现题解的主流是使用二分搜索,所以我也用这种思路重新写了代码:
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
low, high = 0, len(nums)-1
while low <= high:
mid = (low + high) // 2
if nums[mid] == target:
return mid
elif nums[mid] > target:
high = mid - 1
else:
low = mid + 1
return low