首页 > 其他 > 详细

Leetcode 002-Search Insert Position

时间:2018-05-29 22:09:15      阅读:148      评论:0      收藏:0      [点我收藏+]
 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))

最快就是用二分法

Leetcode 002-Search Insert Position

原文:https://www.cnblogs.com/hustcser/p/9108025.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!