您的位置:首页 > 其它

lintcode:Merge Sorted Array

2015-10-14 20:55 295 查看
Given two sorted integer arrays A and B, merge B into A as one sorted array.

Example

A = [1, 2, 3, empty, empty], B = [4, 5]

After merge, A will be filled as [1, 2, 3, 4, 5]

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.

1.提交1

class Solution {
public:
/**
* @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
*/
void mergeSortedArray(int A[], int m, int B[], int n) {
// write your code here
int *res=new int[m+n];
for(int i=0;i<m;i++){
res[i]=A[i];
}

for(int i=m;i<m+n;i++){
res[i]=B[i-m];
}

sort(res,res+m+n);//

memcpy(A,res,sizeof(int)*(m+n));
delete []res;
}
};


虽然AC,但很明显未充分利用有序的特点

2.提交2

class Solution {
public:
/**
* @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
*/
void mergeSortedArray(int A[], int m, int B[], int n) {
// write your code here
//上个实现明显不好
//其实这个就是归并排序的归并阶段
int pa=m-1,pb=n-1,p=m+n-1;
while(pa>=0&&pb>=0){
if(A[pa]>=B[pb]){
A[p]=A[pa];
p--;
pa--;
}else{
A[p]=B[pb];
p--;
pb--;
}
}

while(pa>=0){
A[p--]=A[pa--];
}
while(pb>=0){
A[p--]=B[pb--];
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: