题目:
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 nrespectively.
解题思路1:设置一个数组C,依次取A的元素i与B的元素j比较,如果B[j]小,则将B[j]放入C,再取B的后一个元素与A[i]比较;反之,若A[i]更小,则将A[i]放入C,取A的下一个元素与B[j]比较。比较完成后,将C复制到数组A。该解法的时间复杂度为O(m+n),空间复杂度为O(m+n)
代码1:
class Solution {
public:
void merge(int A[], int m, int B[], int n) {
int C[m+n];
int i=0,j=0,k=0;
while(i<m&&j<n){
if(A[i]<B[j]){
C[k++]=A[i++];
}else{
C[k++]=B[j++];
}
}
while(i<m){
C[k++]=A[i++];
}
while(j<n){
C[k++]=B[j++];
}
for(i=0;i<m+n;i++){
A[i]=C[i];
}
}
};
解题思路2:将A和B的元素逐个从后往前比较,选出大的放在A数组尾部(从m+n-1位置处开始放),这样一来就不需要单独开辟存储空间来存储中间结果了。且不需要移位。时间复杂度O(m+n),空间复杂度O(1)
代码2:
class Solution {
public:
void merge(int A[], int m, int B[], int n) {
int mn=m+n;
int ptr_a=m-1,ptr_b=n-1,ptr_mn=m+n-1;
while(ptr_a>=0&&ptr_b>=0){
A[ptr_mn--]=A[ptr_a]>B[ptr_b]?A[ptr_a--]:B[ptr_b--];
}
while(ptr_b>=0){
A[ptr_mn--]=B[ptr_b--];
}
}
};