如果序列是乱序的,求一个序列中和为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;
}
本文介绍了一种利用归并排序算法解决数组中寻找两个数之和等于特定值x的问题的方法,并提供了详细的代码实现。通过修改归并排序的合并过程,可以在O(nlogn)的时间复杂度内解决此类问题。
361

被折叠的 条评论
为什么被折叠?



