"One Day together Leetcode" #35. Search Insert Position

Source: Internet
Author: User

One Day Together Leetcode series (i) Title

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would >be 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

(ii) Problem solving
/* The idea is that if the target number is greater than the maximum number in the vector, the length of the vector is returned, that is, if the target is less than the minimum number in the vector, it returns 0, that is, inserted at the front if the vector range, the binary method is found, If there is an equal to target, return its ordinal, and if not, exit at I=j, return I indicates the target's insertion position * /classSolution { Public:intSearchinsert ( vector<int>& Nums,intTarget) {intLen = Nums.size ();if(Target > nums[len-1])returnLenif(Target < nums[0])return 0;inti =0;intj = len-1; while(I&LT;=J) {intMid = (i+j)/2;if(Nums[mid] = = target)returnMidElse if(Nums[mid]>target) j=mid-1;Elsei = mid+1; }returnI }};

"One Day together Leetcode" #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.