#include <iostream>
void quickSort(int *, int , int );
bool hasArrayTwoCandidates(int A [], int arrSize , int sum )
{
int l, r;
//对数组元素进行排序
quickSort( A, 0, arrSize - 1);
//在已排序数组中查找这两个元素
l = 0;
r = arrSize - 1;
while (l < r)
{
if ( A[l] + A[r] == sum)
return 1;
else if ( A[l] + A[r] < sum)
l++;
else // A[i] + A[j] > sum
r--;
}
return 0;
}
int main()
{
int A[] = { 1, 4, 45, 6, 10, -8 };
int sum = 16;
int arrSize = 6;
if (hasArrayTwoCandidates(A, arrSize, sum))
std::cout << "Array has two elements with sum 16\n" ;
else
std::cout << "Array doesn't have two elements with sum 16\n" ;
return 0;
}
//下面的代码用于实现快速排序。
void exchange(int *a , int *b )
{
int temp = * a;
* a = * b;
* b = temp;
}
//数组最后元素做为mid元素,进行排序
int partition(int A [], int si , int ei )
{
int x = A[ ei];
int i = ( si - 1);
for ( int j = si; j <= ei - 1; j++)
{
if ( A[j] <= x)
{
i++;
exchange(& A[i], & A[j]);
}
}
exchange(& A[i + 1], & A[ ei]);
return (i + 1);
}
/* 快速排序的实现
A[] --> Array to be sorted
si --> Starting index
ei --> Ending index
*/
void quickSort(int A [], int si , int ei )
{
int pi; //Partitioning index
if ( si < ei)
{
pi = partition( A, si, ei);
quickSort( A, si, pi - 1);
quickSort( A, pi + 1, ei);
}
}#include <iostream>
#define MAX 10000
void findPairs(int arr[], int arrSize, int sum)
{
//定义并初始这个map
bool binMap[MAX];
memset(binMap, 0, sizeof(binMap) / sizeof(bool));
for (int i = 0; i < arrSize; i++)
{
int temp = sum - arr[i];
if (temp >= 0 && binMap[temp])
{
std::cout << "Pair with given sum " << sum << " is (" << arr[i] << ", " << temp << ")\n";
}
binMap[arr[i]] = true;
}
}
int main()
{
int A[] = { 1, 4, 45, 6, 10, 8 };
int n = 53;
int arr_size = sizeof(A) / sizeof(int);
findPairs(A, arr_size, n);
return 0;
}输出:原文:http://blog.csdn.net/shltsh/article/details/46485063