Leetcode 002-Search Insert Position
1 #Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. 2 def searchInsert(nums, target): 3 left=0 4 right=len(nums)-1 5 while left <=right: 6 mid=(right-left)/2+left 7 if nums[mid]==target: 8 return mid 9 elif nums[mid]>target: 10 right=mid-1 11 else: 12 left=mid+1 13 return left 14 L=[1,3,5,6] 15 print(searchInsert(L,5)) 16 print(searchInsert(L,2)) 17 print(searchInsert(L,7)) 18 print(searchInsert(L,0))
最快就是用二分法
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步