Simple C++ solution using maps and loops


#1
  1. vector<int> Solution::solve(vector<int> &A, vector<int> &B, vector<int> &C) {
  2. map<int,int> m1;
  3. map<int,int> m2;
  4. map<int,int> m3;
  5. for(int i=0;i<A.size();i++)
  6. {
  7. if(m1.find(A[i])==m1.end())
  8. {
  9. m1[A[i]]=1;
  10. }
  11. }
  12. // cout<<" 1 \n";
  13. // for(auto gg=m1.begin();gg!=m1.end();gg++)
  14. // {
  15. // cout<<gg->first<<" ";
  16. // }
  17. // cout<<"\n";
  18. for(int i=0;i<B.size();i++)
  19. {
  20. if(m2.find(B[i])==m2.end())
  21. {
  22. m2[B[i]]=1;
  23. }
  24. }
  • for(int i=0;i<C.size();i++)
  1. {
  2. if(m3.find(C[i])==m3.end())
  3. {
  4. m3[C[i]]=1;
  5. }
  6. }
  7. map<int,int> ansMap;
  8. for(auto itr=m1.begin();itr!=m1.end();itr++)
  9. {
  10. if(m2.find(itr->first)!=m2.end() || m3.find(itr->first)!=m3.end())
  11. {
  12. ansMap[itr->first]=1;
  13. }
  14. }
  15. for(auto itr=m2.begin();itr!=m2.end();itr++)
  16. {
  17. if(m1.find(itr->first)!=m1.end() || m3.find(itr->first)!=m3.end())
  18. {
  19. ansMap[itr->first]=1;
  20. }
  21. }
  22. for(auto itr=m3.begin();itr!=m3.end();itr++)
  23. {
  24. if(m2.find(itr->first)!=m2.end() || m1.find(itr->first)!=m1.end())
  25. {
  26. ansMap[itr->first]=1;
  27. }
  28. }
  29. vector<int> ans;
  30. auto it=ansMap.begin();
  31. for(;it!=ansMap.end();it++)
  32. {
  33. // cout<<it->first<<" \n";
  34. ans.push_back(it->first);
  35. }
  36. return ans;
  37. }

#2

no need of three map
we can do in single map


#3

vector Solution::solve(vector &A, vector &B, vector &C) {
unordered_map<int,int> ma,mb,mc;
int maxV =0;
for(int i=0;i<A.size();i++){
ma[A[i]]++;
maxV = max(maxV , A[i]);
}
for(int i=0;i<B.size();i++){
mb[B[i]]++;
maxV = max(maxV , B[i]);
}
for(int i=0;i<C.size();i++){
mc[C[i]]++;
maxV = max(maxV , C[i]);
}
vector ans;
for(int i=1;i<=maxV ;i++){
if( (ma[i]>0 && mb[i]>0) || (ma[i]>0 && mc[i]>0) || (mb[i]>0 && mc[i]>0))
ans.push_back(i);
}
return ans;
}


#4

Nice and Understandable Solution. Thanks.