Topic Link: Merge Sorted Array
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 was greater or equal to M + N) to the hold additional elements from B. The number of elements initialized in A and B is M and N respectively.
The requirement of this problem is to merge the ordered array B into the ordered array A, assuming that a has enough space to accommodate all the elements in B.
Merge the steps of merging in the sort, but because it is to be merged into a, that is, to not apply for additional space, so in order to reduce the number of moving a heavy elements, consider gradually merging from backward to forward: from the backward to the A and B arrays, each time the large number from a m+n position gradually forward.
Complexity of Time: O (m+n)
Space complexity: O (1)
1 class Solution2 {3 Public:4 void Merge(int A[], int m, int B[], int N)5 {6 int I = m - 1, J = N - 1, k = m + N - 1;7 while(J >= 0)8 {9 if(I >= 0 && A[I] > B[J])Ten A[k --] = A[I --]; One Else A A[k --] = B[J --]; - } - } the };
Reprint please indicate source: Leetcode---88. Merge Sorted Array
Leetcode---88. Merge Sorted Array