Given two sorted integer arrays A and B, merge B into A as one sorted array.
** Notice
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.
ExampleA = [1, 2, 3, empty, empty]
, B = [4, 5]
After merge, A will be filled as [1, 2, 3, 4, 5]
合并两个排序好的数组,而且题目说明数组A的side大于m+n; 所以我们用的方法就是从两个数组最后一个数字比起,大的就放到m+n-1的位置去,然后调整index之后继续比下去直到一个数组先空为止,在判断把另一个有剩余的数组填进去。
class Solution {
/**
* @param A: sorted integer array A which has m elements,
* but size of A is m+n
* @param B: sorted integer array B which has n elements
* @return: void
*/
public void mergeSortedArray(int[] A, int m, int[] B, int n) {
// write your code here
int i = m-1, j = n-1, k = m+n-1;
while(i >= 0 && j >= 0){
if(A[i] < B[j]){
A[k] = B[j];
k--;
j--;
}else{
A[k] = A[i];
k--;
i--;
}
}
while(i >= 0){
A[k] = A[i];
k--;
i--;
}
while(j >= 0){
A[k] = B[j];
k--;
j--;
}
}
}
网友评论