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.
给出两个排过序的数组A,B要求把B并到A中 题目没有要求空间复杂度 那直接开个数组与A一样大然后再合并到A里就好了。
class Solution {
public:
void merge(int A[], int m, int B[], int n) {
// Note: The Solution object is instantiated only once and is reused by each test case.
int *C = new int[m];
for (int i = 0; i < m; ++i)
{
C[i] = A[i];
}
int i = 0, j = 0, k = 0;
while (j < m && k < n)
{
if (C[j] <= B[k])
A[i++] = C[j++];
else
A[i++] = B[k++];
}
while (j < m) A[i++] = C[j++];
while (k < n) A[i++] = B[k++];
}
};