35.搜索插入位置
每日leetcode(13)
35.搜索插入位置
今天的题目如下
很简单,如果在则调用index()函数,不在的话,这里用两种方法,一种顺序判断法,一种二分判断法,顺序最好达到44ms,二分最好40ms
class Solution:
def searchInsert(self,nums,target):
try:
return nums.index(target)
except:#顺序判断
for i in rang(len(nums)):
if target>nums[i]:
continue
else:
return i
return len(nums)
class Solution:
def searchInsert(self,nums,target):
try:
return nums.index(target)
except:#二分判断
low=0
high=len(nums)-1
while high>=low:
mid=int((low+high)/2)
if target>nums[mid]:
low=mid+1
else:
high=mid-1
return high+1