Posted on 2023-02-20 20:11
Uriel 阅读(23)
评论(0) 编辑 收藏 引用 所属分类:
闲来无事重切Leet Code 、
大水题 、
二分.三分
计算插入一个新数到已经按升序排序的列表中,返回插入位置,直接调用python的bisect_left()或者手写个二分
Python bisect库函数版:
1 #35
2 #Runtime: 33 ms (Beats 67.74%)
3 #Memory: 14.2 MB (Beats 31.43%)
4
5 class Solution(object):
6 def searchInsert(self, nums, target):
7 """
8 :type nums: List[int]
9 :type target: int
10 :rtype: int
11 """
12 return bisect.bisect_left(nums, target)
手写二分:
1 #35
2 #Runtime: 32 ms (Beats 73.34%)
3 #Memory: 14.2 MB (Beats 60.52%)
4
5 class Solution(object):
6 def searchInsert(self, nums, target):
7 """
8 :type nums: List[int]
9 :type target: int
10 :rtype: int
11 """
12 for i in range(0, len(nums)):
13 if nums[i] == target:
14 return i
15 if nums[i] > target:
16 return i
17 return len(nums)