Created
May 22, 2016 12:04
-
-
Save isRuslan/43d6ee4b756e51dbe60ffbd17079c092 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
bool findPairs(int arr[], int n) | |
{ | |
// Create an empty Hash to store mapping from sum to | |
// pair indexes | |
map<int, pair<int, int> > Hash; | |
// Traverse through all possible pairs of arr[] | |
for (int i = 0; i < n; ++i) | |
{ | |
for (int j = i + 1; j < n; ++j) | |
{ | |
// If sum of current pair is not in hash, | |
// then store it and continue to next pair | |
int sum = arr[i] + arr[j]; | |
if (Hash.find(sum) == Hash.end()) | |
Hash[sum] = make_pair(i, j); | |
else // Else (Sum already present in hash) | |
{ | |
// Find previous pair | |
pair<int, int> pp = Hash[sum];// pp->previous pair | |
// Since array elements are distinct, we don't | |
// need to check if any element is common among pairs | |
cout << "(" << arr[pp.first] << ", " << arr[pp.second] | |
<< ") and (" << arr[i] << ", " << arr[j] << ")\n"; | |
return true; | |
} | |
} | |
} | |
cout << "No pairs found"; | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment