Merge Sorted Array

Merge Sorted Array 

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;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值