码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 002-Search Insert Position

时间:2018-05-29 22:47:54      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:else   二分法   ted   where   targe   and   就是   The   return   

 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

标签:else   二分法   ted   where   targe   and   就是   The   return   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!