# 给定两个未排序的数组，找到所有总和为x的对

## 使用案列

```arr1[] = { 3,6,1,4,8,2}

arr2[] = { 2,1,5,7,2,4}

sum = 9```
`(8, 1), (4, 5) (2, 7)`

```arr1[] = { 2,5,1,7,9}

arr2[] = { 3,6,8,1,0}

sum = 7```
`(1, 6), (7, 0)`

## 在两个未排序的数组中查找具有sum = x的所有对的算法

```1. Declare a Set.
2. Insert all the values of array1 into the Set.
3. Traverse the array2.
4. Check if the difference of sum and each number of array2 is present in a set.
5. If present then prints the difference and the current array element.```

## 代码

### C ++代码在两个未排序的数组中查找具有sum = x的所有对

```#include<iostream>
#include<unordered_set>

using namespace std;

void getPairsofSum(int arr1[], int arr2[], int l1, int l2, int sum)
{
unordered_set<int> MAP;
for (int i = 0; i < l1; i++)
MAP.insert(arr1[i]);

for (int j = 0; j < l2; j++)
if (MAP.find(sum - arr2[j]) != MAP.end())
cout << sum - arr2[j] << " "<< arr2[j] << endl;
}
int main()
{
int arr1[] = { 3,6,1,4,8,2};
int arr2[] = { 2,1,5,7,2,4};
int sum = 9;
int l1 = sizeof(arr1) / sizeof(int);
int l2 = sizeof(arr2) / sizeof(int);
getPairsofSum(arr1, arr2, l1, l2, sum);
return 0;
}
```
```8 1
4 5
2 7```

### Java代码在两个未排序的数组中查找具有sum = x的所有对

```import java.util.HashMap;

class PairofSumUnsortedArray
{
public static void getPairsofSum(int arr1[], int arr2[], int l1, int l2, int sum)
{
HashMap<Integer, Integer> MAP = new HashMap<Integer, Integer>();

for (int i = 0; i < l1; i++)
MAP.put(arr1[i], 0);

for (int j = 0; j < l2; j++)
if (MAP.containsKey(sum - arr2[j]))
System.out.println(sum - arr2[j] + " " + arr2[j]);
}
public static void main(String[] args)
{
int arr1[] = { 3,6,1,4,8,2};
int arr2[] = { 2,1,5,7,2,4};
int sum = 9;
getPairsofSum(arr1, arr2, arr1.length, arr2.length, sum);
}
}
```
```8 1
4 5
2 7```

## 复杂度分析

### 时间复杂度

O（最大（n，m）） 哪里 “ n”“m”个 是第一和第二个数组的长度。

### 空间复杂度

O（最大（n，m）） 哪里 “ n”“m”个 是第一和第二个数组的长度。