Easy Java HashMap Solution:)


  • 0
    public String[] findRestaurant(String[] list1, String[] list2) {
            
            Map<String, Integer> map = new HashMap<>();
            Map<String, Integer> fi = new HashMap<>();
            List<String> res = new ArrayList<>();
            int min = Integer.MAX_VALUE;
    
            for (int i = 0; i < list1.length; i++)
                map.put(list1[i], i);
    
            for (int i = 0; i < list2.length; i++) {
    
                if (map.containsKey(list2[i])) {
    
                    int indexsum = map.get(list2[i]) + i;
                    fi.put(list2[i], indexsum);
                    min = Math.min(min, indexsum);
    
                }
    
            }
    
            for (Map.Entry<String, Integer> entrySet : fi.entrySet())
                if (entrySet.getValue() == min)
                    res.add(entrySet.getKey());
                    
            return res.toArray(new String[res.size()]);
    
        }
    

  • 0
    D

    c++

    vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) {
        map<string, int> map1;
        map<string, int> map2;
        vector<string> res;
        int min = INT_MAX;
        for (int i = 0 ; i < list1.size(); i++) {
            string s = list1[i];
            map1[s] = i;
        }
        
        for (int i = 0 ; i < list2.size(); i++) {
            string s = list2[i];
            if (map1.count(s) > 0) {
                int ind = i + map1[s];
                if (ind <= min) {
                    map2[s] = ind;
                    min = ind;
                }
            }
        }
        
        for (auto const& entry : map2) {
            if (entry.second == min) {
                res.push_back(entry.first);
            }
        }
        return res;
    }

Log in to reply
 

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