利用归并排序求解序列中和为X的数有几对

本文介绍了一种利用归并排序算法解决数组中寻找两个数之和等于特定值x的问题的方法,并提供了详细的代码实现。通过修改归并排序的合并过程,可以在O(nlogn)的时间复杂度内解决此类问题。

如果序列是乱序的,求一个序列中和为X的数有几对,可以修改归并排序的合并过程即可,因为合并的过程中比较了任意的两个数。这种思想当然用来求差为x,乘积为x,商为x等类似问题依然有效。时间复杂度为O(nlgn)。

当然也可以先对序列排序(任何排序算法也可以),再从序列两头向中间扫描,也可解决问题,详细请见http://blog.youkuaiyun.com/v_july_v/article/details/6419466

 

下面给出我利用归并排序求解的代码:

//归并排序应用1:求数组中两个数之和为x的有几对
//直接修改merge过程即可
int merge(int *A, int low, int mid, int high, const int x)
{
	int *merge = new int[high-low+1]; //申请合并空间
	if (!merge)
		return -1;
	int i = low, j = mid+1, k = 0, count = 0;
	while (i<=mid && j<=high)
	{
		if (x == A[i]+A[j]) //判断
			count++;
		if (A[i] <= A[j])
			merge[k++] = A[i++];
		else
			merge[k++] = A[j++];
	}
	while(i<=mid)
		merge[k++] = A[i++];
	while(j<=high)
		merge[k++] = A[j++];
	k=0;
	while(low<=high)
		A[low++] = merge[k++];
	delete []merge;
	return count;
}

int countSumX(int *A, int low, int high, const int x)
{
	int count = 0;
	if (low < high)
	{
		int mid = (low+high)/2;
		count += countSumX(A, low, mid, x);
		count += countSumX(A, mid+1, high, x);
		count += merge(A, low, mid, high, x);		
	}
	return count;
}

int countSumX(const int *A, int n, const int x)
{
	int *copyA = new int[n];
	if (!copyA)
		return 0;
	for (int i=0; i<n; i++)
		copyA[i] = A[i];
	int count = countSumX(copyA, 0, n-1, x);
	delete []copyA;
	return count;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值