[Leetcode] Merge Sorted Array (c + +)

Source: Internet
Author: User

Topic:

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

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.

Tag:

Array; Pointers

Experience:

This small problem, at first glance is very simple, but the realization is still some small place, need special attention. First of all, a special place is the merge B in a, and then from the beginning of the merge, the need to insert operations, and then put the rest of a back, because not linked list, obviously inappropriate. But the topic also asked to merge to a, then what to do, the solution is to start from the bottom of a merge, that is, from the large number to the decimal to start the merge.

In concrete execution, our goal is to finish Bmerge, that is, int j = n-1, while (J >= 0) will continue to execute.

When did you choose the element from B, where you have to pay attention to the boundary of a, that is, the elements of a are already exhausted, so there are two things to choose from B:

One is the elements of a (i.e. i < 0), unconditionally select B, and second, when a is not over, there are b[j] > a[i].

1 classSolution {2  Public:3     voidMergeintA[],intMintB[],intN) {4             inti = m-1;5             intj = N-1;6             intk = m + N-1;7             //When B was merged, Job done8              while(J >=0) {9                 //MergeTen                 if(I <0|| B[J] >A[i]) { One                     //When A was done or a was less than B, choose b AA[K] =B[j]; -j--; -}Else { theA[K] =A[i]; -i--; -                 } -k--; +             } -         } +  A};

[Leetcode] Merge Sorted Array (c + +)

Related Article

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.