Given int array & target, return indices of 2 nums that add to target
Ex. nums = [2,7,11,15] & target = 9 -> [0,1], 2 + 7 = 9
At each num, calculate complement, if exists in hash map then return
Time: O(n)
Space: O(n)
*/
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int n = nums.size();
unordered_map<int, int> mp;
for (int i = 0; i < n; i++) {
int complement = target - nums[i];
if (mp.find(complement) != mp.end()) {
return {mp[complement], i};
}
mp.insert({nums[i], i});
}
return {};
}
};