力扣 599 兩個列表的最小索引總和 MAP*****

一層循環就可以利用count find

class Solution {
public:
    vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) {
        vector<string> vec;
        unordered_map<string, int> hashmap;
        int MIN = 2000;
        
        for (int i = 0; i < list1.size(); i++)
            hashmap[list1[i]] = i;
        
        for (int i = 0; i < list2.size(); i++) {
            if (hashmap.count(list2[i]) > 0) {
                if (hashmap[list2[i]] + i < MIN) {
                    vec.clear();
                    MIN = hashmap[list2[i]] + i;
                    vec.push_back(list2[i]);
                }
                else if (hashmap[list2[i]] + i == MIN)
                    vec.push_back(list2[i]);
            }
        }
        
        return vec;
    }
};

超出時間限制

class Solution {
public:
    vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) {
        unordered_map<string,int> mp1;
        unordered_map<string,int> mp2;
        unordered_map<string,int> res;
        int cnt=0;
        vector<string> tmp;
        int i=0;
        for(int i=0;i<list1.size();i++)
        {
            mp1[list1[i]]=i;
        }
        for(int i=0;i<list2.size();i++)
        {
            mp2[list2[i]]=i;
        }
        for(auto c : mp1)
        {
            for(auto s : mp2)
            {
                if(c.first==s.first)
                {
                    cnt=c.second+s.second;
                    res[c.first]=cnt;
                    break;
                }
            }
        }
        int minv=INT_MAX;
        for(auto c : res)
        {
            minv = min(minv,c.second);
        }
        unordered_map<string,int>::iterator p ;
        for(p=res.begin();p!=res.end();p++)
        {
            if(p->second==minv)
            {
                tmp.push_back(p->first);
            }
        }
        return tmp;

    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章