forked from AaqilSh/DSA-Collection
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindPairWithGivenSumArray.cpp
More file actions
42 lines (33 loc) · 980 Bytes
/
FindPairWithGivenSumArray.cpp
File metadata and controls
42 lines (33 loc) · 980 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <unordered_map>
using namespace std;
// Function to find a pair in an array with a given sum using hashing
void findPair(int nums[], int n, int target)
{
// create an empty map
unordered_map<int, int> map;
// do for each element
for (int i = 0; i < n; i++)
{
// check if pair (nums[i], target - nums[i]) exists
// if the difference is seen before, print the pair
if (map.find(target - nums[i]) != map.end())
{
cout << "Pair found (" << nums[map[target - nums[i]]] << ", "
<< nums[i] << ")\n";
return;
}
// store index of the current element in the map
map[nums[i]] = i;
}
// we reach here if the pair is not found
cout << "Pair not found";
}
int main()
{
int nums[] = { 8, 7, 2, 5, 3, 1 };
int target = 10;
int n = sizeof(nums)/sizeof(nums[0]);
findPair(nums, n, target);
return 0;
}