Skip to main content

Two Sum

Problem

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

Solution Approach

Click - to see solution code
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int n = nums.size();
unordered_map<int, vector<int>> mp;
vector<int> ans(2);
for (int i = 0; i < n; i++) {
mp[nums[i]].push_back(i);
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < mp[target - nums[i]].size(); j++) {
if (mp[target - nums[i]][j] != i) {
ans = {i, mp[target - nums[i]][j]};
return ans;
}
}
}
return ans;
}
};