[AlgoExpert] Two Number Sum

Two Number Sum

  • Time : O(n)
  • Space : O(n)
1
2
3
4
5
6
7
8
9
vector<int> twoNumberSum(vector<int> array, int targetSum) {
unordered_set<int> us;
for(auto& a : array) {
if(us.count(targetSum - a))
return {a, targetSum - a};
us.insert(a);
}
return {};
}
  • Time : O(nlogn)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
vector<int> twoNumberSum(vector<int> array, int targetSum) {
sort(begin(array), end(array));
int l = 0, r = array.size() - 1;
while(l < r) {
int sum = array[l] + array[r];
if(sum == targetSum) return {array[l], array[r]};
else if(sum < targetSum) l++;
else r--;
}
return {};
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/10/PS/AlgoExpert/two-number-sum/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.