Given array of n integers and given a number X, find all the unique pairs of elements (a,b), whose summation is equal to X.
The following is my solution, it is O(nLo
C++11, run time complexity O(n):
#include
#include
#include
std::vector> FindPairsForSum(
const std::vector& data, const int& sum)
{
std::unordered_map umap;
std::vector> result;
for (size_t i = 0; i < data.size(); ++i)
{
if (0 < umap.count(sum - data[i]))
{
size_t j = umap[sum - data[i]];
result.push_back({data[i], data[j]});
}
else
{
umap[data[i]] = i;
}
}
return result;
}