Leetcode_num12_search insert position

Source: Internet
Author: User

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

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.