#-*-Coding:utf8-*-
‘‘‘
__author__ = ' [email protected] '
35:search Insert Position
https://oj.leetcode.com/problems/search-insert-position/
Given a sorted array and a target value, return 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 is 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
===comments by dabay===
Two-point lookup.
‘‘‘
Class Solution:
# @param A, a list of integers
# @param target, an integer to be inserted
# @return Integer
def searchinsert (self, A, target):
Left, right = 0, Len (A)-1
While left < right:
M = (left + right)/2
If a[m] = = target:
return m
Elif A[m] < target:
left = m + 1
Else
right = M-1
Else
return [left, left + 1][target > A[left]]
def main ():
Sol = solution ()
Nums = [1,3,5,6]
target = 5
Print Sol.searchinsert (nums, Target)
if __name__ = = ' __main__ ':
Import time
Start = Time.clock ()
Main ()
Print "%s sec"% (Time.clock ()-start)
[Leetcode] [Python]35:search Insert Position