C++ Solution using unordered_map


  • 0
    P
    vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) {
    	unordered_map<string, int> map;
    	int res = INT_MAX;
    	vector<string> resStr;
    	for (int i = 0; i <list1.size(); i++)
    		map[list1[i]] = i;
    	for (int i = 0; i < list2.size(); i++)
    	{
    		if (map.find(list2[i]) != map.end())
    		{
    			cout << list2[i] << endl;
    			int val = map.at(list2[i]) + i;
    			if (res > val)
    			{
    				if (resStr.size()>0) resStr.pop_back();
    				res = val;
    				resStr.push_back(list2[i]);
    			}
    			else if (res == val)
    				resStr.push_back(list2[i]);
    		}
    	}
    	return resStr;
    }

Log in to reply
 

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