Title Description:
Given a sorted array and a target value, the index is returned if the target value is found in the array. If not, return to the location where it will be inserted sequentially.
You can assume that there are no repeating elements in the array.
Have you ever encountered this problem in a real interview? Yes
Sample Example
[1,3,5,6], 5→2
[1,3,5,6], 2→1
[1,3,5,6], 7→4
[1,3,5,6], 0→0
challenges
O (log (n)) time
labelArray sorting Array binary method
Topic Analysis:
Given a sorted array and a target value, the index is returned if the target value is found in the array. If not, return to the location where it will be inserted sequentially.
You can assume that there are no repeating elements in the array.
refer to the code comment.
Source:
Class solution: "" " @param a:a list of integers @param target:an integer to is inserted @return: an I Nteger "" " def searchinsert (self, A, target): # Write your code this if a is None:return None if a = = []: return 0 n = len (A) if a[0] >= target: # The smallest number is greater than target, insert 0, equal, return 0 return 0 # The IF branch here can be omitted # If a[-1] = = target: # Maximum number equals target, return length n-1 # return n-1 # elif A[-1] < target: # Maximum number less than target, insert end, return length n # return n # The rest of the situation, reverse-traverse the list to find the first number less than equals target for the I in Range ( -1,-n,-1): if a[i] > target: # Greater than target, continue to loop continue elif a[i] = = target: # equals, returns N+i, because I is negative, reverse loop return n+i else: return n +i+1 # is less than target, inserts an element after the n+i position, returns n+i+1
Lintcode Python Simple class topic 60. Search Insertion Location