Given two sorted integer arrays A and B, merge B into A as one sorted array.
Note: You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.
The best solution is to work backwards for both arrays. We use the two indices as before, but initialize them to the indices of the last effective number, i.e. m-1 and n-1.
Note: You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.
The best solution is to work backwards for both arrays. We use the two indices as before, but initialize them to the indices of the last effective number, i.e. m-1 and n-1.
public void merge(int A[], int m, int B[], int n) {
if (A == null || B == null)
return;
int i = m - 1, j = n - 1, k = m + n - 1;
// Put the larger one into A in reverse order
while (i >= 0 && j >= 0) {
if (B[j] >= A[i])
A[k--] = B[j--];
else
A[k--] = A[i--];
}
// Remaining numbers in B are the smallest
while (j >= 0)
A[k--] = B[j--];
}
[CareerCup] 11.1 Merge Arrays 合并数组void merge(vector<int> &a, int m, vector<int> &b, int n) { int cnt = m + n - 1; --m; --n; while (m >= 0 && n >= 0) a[cnt--] = a[m] > b[n] ? a[m--] : b[n--]; while (n >= 0) a[cnt--] = b[n--]; }Read full article from LeetCode - Merge Sorted Array | Darren's Blog