Question:
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it wocould be if it were inserted in order.
You may assume no duplicates in the array.
The intuitive method is as follows:
Class solution: # @ Param a, a list of integers # @ Param target, an integer to be inserted # @ return integer def searchinsert (self, A, target ): rs = 0 # result 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
However, the complexity of this method is O (n)
The method whose complexity is O (logn) requires the use of the binary method.
The Code is as follows:
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
Leetcode_num12_search insert position