Search Insert Position Solution

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

Solution 1--Naive

Iterate the array and compare target with ith and (i+1) th element. Time complexity O (n).

1  Public classSolution {2      Public intSearchinsert (int[] Nums,inttarget) {3         if(nums==NULL)return0;4         if(Target <= nums[0])return0;5          for(inti=0; i<nums.length-1; i++){6             if(Target > Nums[i] && target <= nums[i+1]){7                 returnI+1;8             }9         }Ten         returnnums.length; One     } A}
Solution 2--Binary Search

If the target number doesn ' t exist in original array and then after iteration, it must is pointed by low pointer.

Time Complexity O (log (n))

1  Public classSolution {2      Public intSearchinsert (int[] Nums,inttarget) {3         if(Nums = =NULL|| Nums.length = = 0)4             return0;5         intStart = 0, end = nums.length-1, Mid = (End-start)/2 +start;6          while(Start <=end) {7Mid = (End-start)/2 +start;8             if(Nums[mid] = =target)9                 returnmid;Ten             Else if(Nums[mid] <target) OneStart = mid + 1; A             Else -End = Mid-1; -         } the         returnstart; -     } -}

Search Insert Position Solution

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.