Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Pairs with given sum
//Title of this code #include <algorithm> #include <iostream> #include <set> #include <vector> using namespace std; // O(n^2) void pairs_with_given_sum(const vector<int>& t, int sum) { set<string> s; for (int i = 0; i < t.size() - 1; ++i) for (int j = i + 1; j < t.size(); ++j) if (t[i] + t[j] == sum) { //ut << t[i] << " - " << t[j] << endl; s.insert(to_string(t[i]) + " " + to_string(t[j])); } for (auto it = s.begin(); it != s.end(); ++it) cout << *it << endl; } // O(nlog(n) + n) void pairs_with_given_sum2(vector<int>& t, int sum) { sort(t.begin(), t.end()); /* for (auto it=t.begin(); it!=t.end(); ++it) cout << *it << " "; cout << endl; */ int i = 0; int j = t.size() - 1; int latest = 0; while (i < j) { int num = t[i] + t[j]; if (num > sum) --j; else if (num < sum) ++i; else { if (latest != t[j]) cout << t[i] << " " << t[j] << endl; latest = t[j]; ++i; } } } int main() { vector<int> t; t.push_back(4); t.push_back(1); t.push_back(2); t.push_back(3); t.push_back(2); t.push_back(5); t.push_back(3); t.push_back(0); t.push_back(3); pairs_with_given_sum(t, 5); cout << endl; pairs_with_given_sum2(t, 5); }
run
|
edit
|
history
|
help
0
bitmap with pairs
Filtering a vector attribute with template UnaryPredicate
float precision test
Subarray with 0 sum
FindKthElementDivideConquer
Binary search on sorted array
Sum of digits of number
Dar
LRU cache
шаблонизированное наследование