C++ easy O(n) solution, only one hashap


  • 0
    M
        vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) {
            vector<string> res;
            unordered_map<string, int> dict;
            for(int i=0;i<list1.size();i++) dict[list1[i]]=i+1;
            for(int i=0;i<list2.size();i++) {
                if(dict.find(list2[i])!=dict.end()) dict[list2[i]]+=i+1;
            }
            for(int i=0;i<list1.size();i++) {
                if(dict[list1[i]]==i+1) dict[list1[i]]=INT_MAX;
            }
            int cur=INT_MAX;
            for(unordered_map<string, int>::iterator p=dict.begin();p!=dict.end();p++) {
                if(p->second==cur) res.push_back(p->first);
                else if(p->second<cur) {
                    cur=p->second;
                    res.clear();
                    res.push_back(p->first);
                }
            }
            return res;
        }

Log in to reply
 

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