题目:
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.
You may assume no duplicates in the array.
比较直观的方法如下:class Solution:
# @param A, a list of integers
# @param target, an integer to be inserted
# @return integer
def searchInsert(self, A, target):
rs=0 #结果
L=len(A)
for i in range(L):
if target<A[0]:
rs=0
break
elif target>A[L-1]:
rs=L
break
elif target==A[i]:
rs=i
break
elif target>A[i] and target<A[i+1]:
rs=i+1
break
return rs
但是该方法的复杂度为o(n)
复杂度为o(logn)的方法需要利用二分法
代码如下:
class Solution:
# @param A, a list of integers
# @param target, an integer to be inserted
# @return integer
def searchInsert(self, A, target):
L=len(A)
low=0
high=L-1
while(low<=high):
mid=low+(high-low)/2
if target<A[mid]:
high=mid-1
elif target>A[mid]:
low=mid+1
else:
return mid
return low