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--];
}
Read full article from LeetCode - Merge Sorted Array | Darren's Blog
No comments:
Post a Comment