Leetcode OJ 35. Search Insert Position

Source: Internet
Author: User

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

"Problem Analysis"

Given a sorted array, there are no duplicate numbers in the array. Given a number to find the position where the number appears, if the number does not exist in the array, it returns where the number should be inserted if it is inserted.

Ideas

When it comes to sorted arrays, we generally use a binary lookup algorithm. If the target number is present, the result is returned directly. What if it doesn't exist?

Look at the binary search, left and right are equal, if the value and the target value at the same time, left is the result should be returned, otherwise we compare the target value and subscript left corresponding to the value of the size. Returns LEFT+1 if the target value is large, otherwise returns left.

"Java Code"

1  Public classSolution {2      Public intSearchinsert (int[] Nums,inttarget) {3         if(Nums.length = = 0 | | nums = =NULL)return0;4         5         intleft = 0;6         intright = Nums.length-1;7         8          while(Left <=Right ) {9             if(left = =Right ) {Ten                 if(Nums[left] = = target)returnLeft ; One                 Else  Break; A             } -             intMid = (Right-left)/2 +Left ; -             if(Nums[mid] > target) right = Mid-1; the             Else if(Nums[mid] < target) left = mid + 1; -             Else returnmid; -         } -         if(Nums[left] < target)returnLeft+1; +         Else returnLeft ; -     } +}

Leetcode OJ 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.