C++ O(n) using one hashmap


  • 0
    M
    
    class Solution {
    public:
        vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) {
            unordered_map<string, int> mymap;
            int mymin = INT_MAX;
            vector<string> ans;
            for(int i = 0; i < list1.size(); i++) mymap[list1[i]] = i;
            for(int i = 0; i < list2.size(); i++){
                if(mymap.find(list2[i]) != mymap.end()){
                    if(mymin > i + mymap[list2[i]]){
                        mymin = i + mymap[list2[i]];
                        ans.clear();
                        ans.push_back(list2[i]);
                    }
                    else if(mymin == i + mymap[list2[i]]){
                        ans.push_back(list2[i]);
                    }
                }
            }
            return ans;
        }
    };
    
    

Log in to reply
 

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