I wrote the following to find two elements that sum to K
#include
#include
void sum_equal_to_k(int *a, int n, int k) { /*
The problem is known as 3SUM
. There's an O(n^2)
algorithm for solving it that you can find here, that doesn't require any hashing.
It'll be simpler if you just use vector
(you're already using unordered_map
anyway, right?):
void sum3_k(std::vector<int> s, int k) {
std::sort(s.begin(), s.end());
for (size_t i = 0; i < s.size() - 2; ++i) {
size_t start = i + 1;
size_t end = s.size() - 1;
while (start < end) {
int sum = s[i] + s[start] + s[end];
if (sum == k) {
std::cout << s[i] << " " << s[start] << " " << s[end] << std::endl;
++start, --end;
}
else if (sum > k) {
--end;
}
else {
++start;
}
}
}
}