[Lintcode Easy] Merge Sorted Array

Source: Internet
Author: User
Tags lintcode

Merge Sorted Array

Given sorted integer arrays A and B, merge B into a as one sorted array.

Has you met this question in a real interview?YesWhich company asked do you question?AirbnbAlibabaAmazonAppleBaiduBloombergCiscoDropboxEbayFacebook Google Hulu Intel Linkedin Microsoft NetEase Nvidia Oracle Pinterest Snapchat Tencent Twitter Uber Xiaomi Yahoo Yelp Zenefits Thanks for your feedback. Example

A = [1, 2, 3, empty, empty] , B =[4, 5]

After merge, A'll be filled as[1, 2, 3, 4, 5]

Note

You could assume that A have enough space (size that's greater or equal to m + n) to the hold additional Eleme NTS from B. The number of elements initialized in A and B is m and n respectively.

Because It is sorted array, we can compare them from the end to the start.

Which one is greater, put it in the last array A

Keep decreasing M and n

Until M or n equal to 0

If m=0, copy all of the numbers in array B to A;

classSolution {/**     * @parama:sorted Integer array A which have m elements, * but size of a is m+n *@paramb:sorted integer array B which has n elements *@return: void*/     Public voidMergesortedarray (int[] A,intMint[] B,intN) {//Write your code here         while(m>0&&n>0)        {           if(a[m-1]>b[n-1]) {a[m+n-1]=a[m-1]; M--; }           Else{a[m+n-1]=b[n-1]; N--; }        }                 while(n>0) {a[m+n-1]=b[n-1]; N--; }            }}

[Lintcode Easy] Merge Sorted Array

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.