Clean C++ solution with unordered_map


  • 0
    J
    class Solution {
    public:
        vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) {
            vector<string> res;
            if(list1.size() == 0 || list2.size() == 0) return res;
            unordered_map<string, int> stridx1;
            for(int i = 0; i < list1.size(); i++)
                stridx1[list1[i]] = i;
            int minidxsum = INT_MAX;
            unordered_map<string, int> stridx2;
            for(int i = 0; i < list2.size(); i++) {
                if(stridx1.count(list2[i]) > 0) {
                    minidxsum = min(minidxsum, stridx1[list2[i]]+i);
                    stridx2[list2[i]] = i;
                }
            }
            for(auto it = stridx2.begin(); it != stridx2.end(); it++) {
                if(it->second + stridx1[it->first] == minidxsum)
                    res.push_back(it->first);
            }
            return res;
        }
    };
    

Log in to reply
 

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