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