Advertisement
minh_tran_782

Bai3_MakePair_Hash

Nov 14th, 2021
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.14 KB | None | 0 0
  1. bool findPairs(int arr[], int n, pair<int,int>& pair1, pair<int, int>& pair2)
  2. {
  3.     // Create an empty Hash to store mapping from sum to
  4.     // pair indexes
  5.     map<int, pair<int, int> > Hash;
  6.     // Traverse through all possible pairs of arr[]
  7.     for (int i = 0; i < n; ++i)
  8.     {
  9.         for (int j = i + 1; j < n; ++j)
  10.         {
  11.             // If sum of current pair is not in hash,
  12.             // then store it and continue to next pair
  13.             int sum = arr[i] + arr[j];
  14.             if (Hash.find(sum) == Hash.end())
  15.                 Hash[sum] = make_pair(i, j);
  16.  
  17.             else // Else (Sum already present in hash)
  18.             {
  19.                 // Find previous pair
  20.                 pair<int, int> pp = Hash[sum];// pp->previous pair
  21.  
  22.                 // Since array elements are distinct, we don't
  23.                 // need to check if any element is common among pairs
  24.                 pair1.first = arr[pp.first];
  25.                 pair1.second = arr[pp.second];
  26.                 pair2.first = arr[i];
  27.                 pair2.second = arr[j];
  28.                 return true;
  29.             }
  30.         }
  31.     }
  32.     return false;
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement