Easy C++ Solution using Maps and Simple Loops


#1

Using Maps and simple loops, below code
vector Solution::solve(vector &A, vector &B, vector &C) {
map<int,int> m1;
map<int,int> m2;
map<int,int> m3;

//First adding all the unique elements into their respective maps

for(int i=0;i<A.size();i++)
{
    if(m1.find(A[i])==m1.end())
    {
        m1[A[i]]=1;
    }
}
// cout<<" 1 \n";
// for(auto gg=m1.begin();gg!=m1.end();gg++)
// {
//     cout<<gg->first<<" ";
// }
// cout<<"\n";
for(int i=0;i<B.size();i++)
{
    if(m2.find(B[i])==m2.end())
    {
        m2[B[i]]=1;
    }
}

for(int i=0;i<C.size();i++)
{
    if(m3.find(C[i])==m3.end())
    {
        m3[C[i]]=1;
    }
}
map<int,int> ansMap;
//Now checking if this item appears in the either of the two maps 
for(auto itr=m1.begin();itr!=m1.end();itr++)
{
    if(m2.find(itr->first)!=m2.end() || m3.find(itr->first)!=m3.end())
    {
        ansMap[itr->first]=1;
    }
}
for(auto itr=m2.begin();itr!=m2.end();itr++)
{
    if(m1.find(itr->first)!=m1.end() || m3.find(itr->first)!=m3.end())
    {
        ansMap[itr->first]=1;
    }
}
for(auto itr=m3.begin();itr!=m3.end();itr++)
{
    if(m2.find(itr->first)!=m2.end() || m1.find(itr->first)!=m1.end())
    {
        ansMap[itr->first]=1;
    }
}
vector<int> ans;
//Adding the unique items in increasing order into the vecotr
auto it=ansMap.begin();
for(;it!=ansMap.end();it++)
{
    // cout<<it->first<<" \n";
    ans.push_back(it->first);
}
return ans;

}


#2

YEs thankyou for the solution


#3

linear time using only one map

vector Solution::solve(vector &a, vector &b, vector &c) {

map<int,vector<int> > m;
for(int i=0;i<a.size();i++){
    if(m[a[i]].size()==0)
    m[a[i]].push_back(1);
}

for(int i=0;i<b.size();i++){
    if(m[b[i]].size()<2){
        if(m[b[i]].size()==0 || m[b[i]][0]!=2){
            m[b[i]].push_back(2);
        }
    }
    
}
for(int i=0;i<c.size();i++){
    if(m[c[i]].size()==1){
        m[c[i]].push_back(3);
    }
}

vector<int> v;
for(auto it=m.begin();it!=m.end();it++){
    if(it->second.size()>1){
        v.push_back(it->first);
    }
}
//sort(v.begin(),v.end());
return v;

}