My Solution with great approach and easy implementation


#1

vector Solution::twoSum(const vector &A, int B) {
map<int,vector>m;
for(int i=0;i<A.size();i++)
{
m[A[i]].push_back(i+1);
}
vector<pair<int,int>>v;
for(int i=A.size()-1;i>=0;i–)
{

    int q=B-A[i];
    // cout<<A[i]<<" "<<q<<endl;
    if(q!=A[i])
    {
    if(m[q].size()!=0&&m[A[i]].size()!=0)
    {
       
        v.push_back(make_pair(m[q][0],m[A[i]][0]));
    }
    }
    else
    {
        if(m[q].size()>=2)
    {
       
        v.push_back(make_pair(m[q][0],m[q][1]));
    }
    }
    
}
// cout<<v.size()<<endl;

// for(int i=0;i<v.size();i++)
// cout<<v[i].first<<" "<<v[i].second<<endl;

vector<int>u;
if(v.size()==0)
{
    return u;
}
sort(v.begin(),v.end());
int ma=A.size(),mi=A.size();

for(int i=0;i<v.size();i++)
{
if(v[i].second>v[i].first&&v[i].second<ma||v[i].first<mi)
{
ma=v[i].second;
mi=v[i].first;
}
}
u.push_back(mi);
u.push_back(ma);
return u;

}