計(jì)算插入一個(gè)新數(shù)到已經(jīng)按升序排序的列表中,返回插入位置,直接調(diào)用python的bisect_left()或者手寫(xiě)個(gè)二分
Python bisect庫(kù)函數(shù)版:
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)
手寫(xiě)二分:
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)