[Work@] Two Sum

Two Sum

Given an array A and an integer target, find the indices of the two numbers in the array whose sum is equal to the given target.

Note: The problem has exactly one solution. Do not use the same element twice.

1
2
3
4
5
6
7
8
pair<int,int> twoSum(vector<int> &A, int target) {
unordered_map<int, int> mp;
for(int i = 0; i < A.size(); i++) {
if(mp.count(target - A[i])) return {mp[target - A[i]], i};
mp[A[i]] = i;
}
return {-1,-1};
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/04/PS/WorkAt/two-sum/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.