C++ Two Sum using HashMap














































C++ Two Sum using HashMap



                                                                   Two Sum

Given an  array of integers and an integer target. Return the indices of the two numbers such that they add up to target.
write an efficient algorithm to solve the above problem.
We can Print indices in any order like (0,1) or (1,0).

Program :

#include<bits/stdc++.h>
using namespace std;
void twosum(vector<int>nums,int k)
{
map<int,int>mp;
vector<int>v;
for(int i=0;i<nums.size();i++)
{
if(mp.find(k-nums[i])!=mp.end() )
{
v.push_back(i);
v.push_back(mp[k-nums[i]]);
break;
}
else
mp[nums[i]]=i;;
}
for(int i=0;i<v.size();i++)
{
cout<<v[i]<<" ";
}

}
int main()
{
vector<int> ele;
ele.push_back(
2);
ele.push_back(
7);
ele.push_back(
0);
ele.push_back(
5);
ele.push_back(
1);
int target=9;
twosum(ele,target);
}


Output:




Comments