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 to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.
Solution:
If we start from the beginning of array A, it would disturb A's structure.
So we will start from the end of array A after A has expanded it array size.
You may assume that A has enough space to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.
Solution:
If we start from the beginning of array A, it would disturb A's structure.
So we will start from the end of array A after A has expanded it array size.
public class Solution {
public void merge(int A[], int m, int B[], int n) {
if (n == 0) return;
int length = m + n - 1;
m--;
n--;
while(length >= 0){
if (n < 0) return;
else if ((m < 0) && (n >= 0)) {
A[length] = B[n];
n--;
}
else if(A[m] > B[n]) {
A[length] = A[m];
m--;
}
else{
A[length] = B[n];
n--;
}
length--;
}
}
}
No comments:
Post a Comment