Skip to content

Instantly share code, notes, and snippets.

@misgeatgit
Created October 15, 2018 18:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save misgeatgit/e77c0b8e0b64aec4249e0a1d4ae4d64c to your computer and use it in GitHub Desktop.
Save misgeatgit/e77c0b8e0b64aec4249e0a1d4ae4d64c to your computer and use it in GitHub Desktop.
#include <algorithm>
#include <iostream>
#include <vector>
std::pair<int,int> find_sum(int sum, std::vector<int> aray)
{
std::vector<int> temp = aray;
std::sort(temp.begin(), temp.end()); // Ascending order
int i1; int i2;
// N * log(N)
for(int i = 0; i < temp.size(); i++)
{
int remaining = sum - temp[i];
auto it = std::find_if(temp.begin()+i, temp.end(),[=](int e) { return e == remaining;});
if(it != temp.end())
{
i1 = i;
i2 = it - temp.begin();
break;
}
}
// find the original index 2*log(N)
auto it = std::find_if(aray.begin(), aray.end(), [=](int x){ return temp[i1] == x;});
i1 = it - aray.begin();
it = std::find_if(aray.begin(), aray.end(), [=](int x){ return temp[i2] == x;});
i2 = it - aray.begin();
// 2*log(N) + N*log(N) ~ N*log(N)
return std::make_pair(i1,i2);
}
int main()
{
std::vector<int> test = {1,2,5,4,8,6};
auto p = find_sum(5, test);
std::cout << "(" << p.first << "," << p.second << ")\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment