"Leetcode with Python" Search Insert Position__python

Source: Internet
Author: User
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 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.