Easy C++ solution with O(m+n)


  • 0
    A
    public:
        vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) {
                
                vector<pair<int,int>> c;
                int index=INT_MAX,i;
                vector<string> s;
                for(i=0;i<list1.size();i++)
                {
                    auto it=find(list2.begin(),list2.end(),list1[i]);
                    if( it!=list2.end())
                    c.push_back(make_pair(i,it-list2.begin()));
                    
                }
                for(i=0;i<c.size();i++)
                {
                    if(index >= c[i].first+c[i].second)
                    {
                        index=c[i].first+c[i].second;
                        s.push_back(list1[c[i].first]);
                    }
                }
             return s;          
        }
    };```

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.