Blog Domain name: Http://www.xnerv.wang
Original title page: https://oj.leetcode.com/problems/search-insert-position/
Topic type: Two-point search
Difficulty Evaluation: ★
This article address: http://blog.csdn.net/nerv3x3/article/details/39453389
Given a sorted array and a target value, return the the index if the target is found. If not, return the index where it would is if it were inserted in order.
Assume no duplicates in the array.
Here are few examples.
[1,3,5,6], 5→2
[1,3,5,6], 2→1
[1,3,5,6], 7→4
[1,3,5,6], 0→0
A variant of the two-point lookup. If target is found, the subscript (normal binary lookup logic) is returned or the inserted position is returned. Two-point search is easy to get dizzy is whether to return to left or right, note that the left will eventually stop on target, or at Target's "location" on the right-hand side, so obviously can not find target, you should return the subscript as the insertion position.
class Solution: # @param A, a list of integers # @param target, an integer to be inserted
# @return Integer def searchinsert (self, A, target): If None = a:return 0 len_a = Len (a)
If Target > A[len_a-1]: Return len_a if Target < A[0]: return 0 left = 0 right = Len_a-1 while left <= right: # also can is left < right mid = (lef
T + right)/2 if A[MID] < Target:left = mid + 1 elif A[mid] > target: right = Mid-1 Else:return mid return left