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))
最快就是用二分法