Leetcode problem 35:search Insert Position

Source: Internet
Author: User

Description: 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

Idea 1: An intuitive idea, traversing an array, once the current element is >=target, the position of the current element is the insertion position, and the boundary problem is dealt with. Time complexity: O (N)

1 classSolution {2  Public:3     intSearchinsert (intA[],intNinttarget) {4 5         if(Target > a[n-1])6             returnN;7             8         Else    {        9              for(inti =0; I < n; i++)  {Ten                 if(A[i] >=target) One                     returni; A             } -         } -     } the};

Idea 2: Because the given array is already ordered, you can use binary search to compare the size of A[mid] with target. Complexity of Time: O (LOGN)

1 classSolution {2  Public:3     intSearchinsert (intA[],intNinttarget) {4         5         intStart =0;6         intEnd = N-1;7         intMID =0;8         9          while(End >=start) {Ten              OneMid = (start + end)/2; A             if(target = =A[mid]) -                 returnmid; -             Else if(Target >A[mid]) theStart = mid +1; -             Else -End = Mid-1; -         } +          -         if(Target >A[mid]) +             returnMid +1; A         Else at             returnmid; -  -     } -};

Leetcode problem 35: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.