[Leetcode]Merge Sorted Array

本文深入探讨了如何高效地将两个已排序的整数数组合并为一个有序数组,通过对比两种不同的方法来优化合并过程,包括尾插法和辅助数组法,并详细解释了其背后的原理和适用场景。

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1and nums2 are m and n respectively.

分析:

1.AB都已是排好序的数,我只需要从后往前比就可以了。A有足的空A + B,我使用游i指向m + n - 1,也就是最大数存放的地方,从后往前遍AB大就放到i里,同时递减i

2.按照归并排序的惯性思路,因为归并排序中给定的是一个数组的两个区间,所以通常情况下会借助O(n)大小的辅助空间。

<pre name="code" class="cpp">#include "utility.h"

class Solution88
{
public:
	void merge(int A[], int m, int B[], int n){
		//采用尾插法,不需要辅助空间
		int icur = m + n - 1;
		int ia = m - 1;
		int ib = n - 1;

		while (ia >= 0 && ib >= 0){
			if (A[ia] >= B[ib]){
				A[icur] = A[ia];
				icur--;
				ia--;
			}
			else{
				A[icur--] = B[ib--];
			}
		}
		while (ib >= 0){
			A[icur--] = B[ib--];
		}
		
	}
	void merge1(int A[], int m, int B[], int n){
		int temp[100];
		int ia = 0, ib = 0, icur = 0;
		while (ia < m&&ib < n){
			if (A[ia] < B[ib])
				temp[icur++] = A[ia++];
			else
				temp[icur++] = B[ib++];
		}
		while (ia < m){
			temp[icur++] = A[ia++];
		}
		while (ib < n){
			temp[icur++] = B[ib++];
		}
		while (--icur>0){
			A[icur] = temp[icur];
		}
	}

};
int main()
{
	Solution88 solution;

	int a1[100] = { 1, 6, 9 };
	int b1[] = { 2, 4, 7 };
	solution.merge1(a1, 3, b1, 3);
	for (int i = 0; i < 6; i++)
		cout << a1[i] << endl;
	
	getchar();
	return 0;
}



评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值