Java HashMap solution


  • 0
    public class Solution {
        public String[] findRestaurant(String[] list1, String[] list2) {
            Map<String, Integer> iMap1 = new HashMap<>();
            Map<String, Integer> iMap2 = new HashMap<>();
            
            for(int i = 0; i < list1.length; i++) {
                iMap1.put(list1[i], i);
            }
            for(int i = 0; i < list2.length; i++) {
                iMap2.put(list2[i], i);
            }
            
            List<String> result = new ArrayList<>();
            int minSum = Integer.MAX_VALUE;
            for(String r : iMap1.keySet()) {
                if(iMap2.get(r) != null) {
                    int i1 = iMap1.get(r);
                    int i2 = iMap2.get(r);
                    if(i1 + i2 < minSum) {
                        minSum = i1 + i2;
                        result.clear();
                        result.add(r);
                    }
                    else if(i1 + i2 == minSum) {
                        result.add(r);
                    }
                }
            }
            
            return result.toArray(new String[result.size()]);
        }
    }
    

Log in to reply
 

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