C++ Using Hash


  • 0
    F
    class Solution {
    public:
        vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) {
            unordered_map<string, int> hash;
            vector<string> result;
            for (int i = 0; i < list1.size(); ++i)
                hash[list1[i]] = i;
            int min_val = INT_MAX;
            for (int i = 0; i < list2.size(); ++i)
            {
                auto iter = hash.find(list2[i]);
                if (iter == hash.end())
                    continue;
                if (iter->second + i < min_val)
                {
                    result.clear();
                    result.push_back(list2[i]);
                    min_val = iter->second + i;
                }
                else if (iter->second + i == min_val)
                    result.push_back(list2[i]);
            }
            return result;
        }
    };
    

Log in to reply
 

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