一开始是用遍历的方法做的:
class Solution:
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if target > nums[len(nums)-1]:
k = len(nums)
else:
for i in range(len(nums)):
if target <= nums[i]:
k = i
return k
return k
后来发现是排序好的列表,应该用二分法平均复杂度最低,于是:
class Solution:
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
first = 0
last = len(nums)-1
if target > nums[last]:
return last + 1
if target <= nums[first]:
return first
while first + 1 < last:
mid = (first + last + 1)//2
if target < nums[mid]:
last -= 1
elif target > nums[mid]:
first +=1
else:
return mid
return last
嘿嘿,昨天开始做leetcode,准备从按照tags难度从低到高做,今天这两道题都是自己解出来的,虽然很简单,但是很开心~