leetcode 哈希表

来源:互联网 发布:r语言导入excel数据 编辑:程序博客网 时间:2024/06/05 21:03

599. Minimum Index Sum of Two Lists

题目描述:两个人选择取餐厅吃饭,他们分别列出自己最倾向的餐厅排序,要求找到一个两个人都尽量喜欢的一个餐厅。

Example 1:

Input:["Shogun", "Tapioca Express", "Burger King", "KFC"]["Piatti", "The Grill at Torrey Pines", "Hungry Hunter Steakhouse", "Shogun"]Output: ["Shogun"]Explanation: The only restaurant they both like is "Shogun".

Example 2:

Input:["Shogun", "Tapioca Express", "Burger King", "KFC"]["KFC", "Shogun", "Burger King"]Output: ["Shogun"]Explanation: The restaurant they both like and have the least index sum is "Shogun" with index sum 1 (0+1).
思路:使用两个map分别保存两个列表,时间复杂度为O(n),空间复杂度O(n)

错误示例:

class Solution {public:    vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) {                unsigned int length1=list1.size(),length2=list2.size();        if(length1>length2)        return getRes(list1,list2);        else return getRes(list2,list1);            }    vector<string> getRes(vector<string>& list1,vector<string> list2){        map<string,int> map1,map2;        int minstring=numeric_limits<int>::max();        vector<string> res;        string tempstring;        for(vector<string>::size_type i=0;i<list2.size();i++)        {            map1[list1[i]]=i;            map2[list2[i]]=i;            int temp=0;            if(map1[list2[i]]!=-1) {                temp=i+map1[list2[i]];                if(minstring>temp)             {                tempstring=list2[i];                minstring=temp;            }            }            if(map2[list1[i]]!=-1){                temp=i+map2[list1[i]];            if(minstring>temp)             {                tempstring=list1[i];                minstring=temp;            }            }                     }        for(auto i=list2.size();i<list1.size();i++)        {            map1[list1[i]]=i;            if(map2[list1[i]]!=-1){                int temp=i+map2[list1[i]];            if(minstring>temp)             {                tempstring=list1[i];                minstring=temp;            }            }        }        res.push_back(tempstring);        return res;    }};
这里不能使用map的下标操作查找一个元素,因为当查找不到时,将添加一个默认值初始化的键值。

解法1:使用unordered_map,先遍历
class Solution {
public:
    vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) {
        
    unordered_map<vector<string>,int> l1;
    for(int i=0;i<list1.size();i++)
    {
        l1[list1[i]]=i;
    }
    unordered_map<int,vector<string>> res;
    int min=list1.size()+list2.size();
    for(int i=0;i<list2.size();i++)
    {
        auto s=l1.find(list2[i]);
        if(s!=l1.end())
        {
            int sum=i+s->second;
            if(min>=sum)
            {
                min=sum;
                res[min].push_back(list2[i]);
            }
        }
    }
    return res[min];
        
    }
    
};

原创粉丝点击