I was thinking about this problem where you should make a function that takes an array and a target value and then it will find all the pair values that sums up to that target value.
Of course there is the naive way using nested loops, but I want to avoid the O(n²) time complexity so I have came up with this solution.
Knowing that
- Array is sorted.
- Length is static (for the testing purpose only)
Particular concerns
does it scale better than O(n²)?
could I do better?
#include <vector> using namespace std; void pairs_sum_up_to_value(int arr[], int target) { int p1 = 0; int p2 = 15; int flag = 2; vector<result> res; while (p1 < p2) { if (arr[p1] + arr[p2] == target) { for (int k = 0; k < res.size() - 1; k++) { if (res.size() == 0) res.push_back(result(arr[p1], arr[p2])); else if (res[k].num1 != arr[p1] && res[k].num2 != arr[p2]) { flag = 1; } else flag = 0; } if(flag == 0) res.push_back(result(arr[p1], arr[p2])); p1++; } else if (arr[p1] + arr[p2] < target) { p1++; continue; } else if (arr[p1] + arr[p2] > target) { p2--; for (int i = p1; i >=0; i--) { if (arr[i] + arr[p2] == target) { res.push_back(result(arr[p1], arr[p2])); } else if (arr[i] + arr[p2] > target) { continue; } else break; } } }
vector
- is that supposed to bestd::vector
?\$\endgroup\$