Merge Sorted Array
Given two sorted integer arrays A and B, merge B into A as one sorted array.
Note:
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 n respectively.
注意点:
在排序的时候,先将大的A数组往后移动,然后从A的头开始往后填。
提交了两次,第一次A数组往后移动的时候顺序错了,应该先把后面的移过去。
别人的解法:
考虑从后往前比较,这样就不会产生需要数据后移的问题了。时间复杂度O(n+m)
我的笨办法:
#include <iostream>
using namespace std;
class Solution {
public:
void merge(int A[], int m, int B[], int n) {
for(int i=m-1;i>=0;i--)
A[n+i]=A[i];
int pa=n;
int pb=0;
int pos=0;
while( pa<m+n && pb<n ){
if(A[pa]<B[pb]){
A[pos]=A[pa++];
}else{
A[pos]=B[pb++];
}
pos++;
}
if(pa == m+n){
while(pos<m+n){
A[pos]=B[pb++];
pos++;
}
}else{
while(pos<m+n){
A[pos]=A[pa++];
pos++;
}
}
}
};
int main(){
int m=5;
int n=1;
int a[6] = {1,2,4,5,6};
int b[1] = {3};
Solution s=Solution();
s.merge(a,5,b,1);
for(int i=0;i<6;++i)
cout<<a[i]<<" ";
cout<<endl;
return 0;
}
#include <iostream>
using namespace std;
class Solution {
public:
void merge(int A[], int m, int B[], int n) {
int pos = m+n-1;
int pa = m-1;
int pb = n-1;
while( pa>=0 && pb>=0 ){
if(A[pa] > B[pb]){
A[pos--] = A[pa--];
}else{
A[pos--] = B[pb--];
}
}
while(pa>=0){
A[pos--] = A[pa--];
}
while(pb>=0){
A[pos--] = B[pb--];
}
}
};
int main(){
int m=5;
int n=1;
int a[6] = {1,2,4,5,6};
int b[1] = {3};
Solution s=Solution();
s.merge(a,5,b,1);
for(int i=0;i<6;++i)
cout<<a[i]<<" ";
cout<<endl;
return 0;
}