描述
合并两个排序的整数数组A和B变成一个新的数组。
你可以假设A具有足够的空间(A数组的大小大于或等于m+n)去添加B中的元素。
样例
给出 A = [1, 2, 3, empty, empty], B = [4, 5]
合并两个排序的整数数组A和B变成一个新的数组。
你可以假设A具有足够的空间(A数组的大小大于或等于m+n)去添加B中的元素。
样例
给出 A = [1, 2, 3, empty, empty], B = [4, 5]
合并之后 A 将变成 [1,2,3,4,5]
分析
用归并排序的思想,先确定返回得到新A数组的大小(m+n),A、B倒序比较,将最大的那个值压入新A数组的最后。因为A中有很多empty,所以A会比B先遍历完,然后将剩下的B全部压入即可。
程序
class Solution {
public:
/*
* @param A: sorted integer array A which has m elements, but size of A is m+n
* @param m: An integer
* @param B: sorted integer array B which has n elements
* @param n: An integer
* @return: nothing
*/
void mergeSortedArray(int A[], int m, int B[], int n) {
// write your code here
int total = m+n;
while(m > 0 && n > 0){
if(A[m-1] < B[n-1]){
A[total - 1] = B[n - 1];
n--;
}
else{
A[total - 1] = A[m - 1];
m--;
}
total--;
}
//A先遍历完,因为里面有很多empty
while(n > 0){
A[total - 1] = B[n - 1];
total--;
n--;
}
}
};