Java Solution Using HashMaps


  • 0
    E
    public class Solution {
        public String[] findRestaurant(String[] list1, String[] list2) {
            HashMap<String, Integer>map1=new HashMap<String, Integer>();
            for(int i=0;i<list1.length;i++){
                map1.put(list1[i],i);
            }
            HashMap<String, Integer>map2=new HashMap<String, Integer>();
            int min=Integer.MAX_VALUE;
            for(int i=0;i<list2.length;i++){
                if(map1.containsKey(list2[i])){
                    map2.put(list2[i],map1.get(list2[i])+i);
                    if(min>map1.get(list2[i])+i){
                        min=map1.get(list2[i])+i;
                    }
                }
            }
            HashSet<String>set=new HashSet<String>();
            for(String key:map2.keySet()){
                if(map2.get(key)==min){
                    set.add(key);
                }
            }
            String arr[]=new String[set.size()];
            int i=0;
            for(String s:set){
                arr[i++]=s;
            }
            return arr;
        }
    }
    

Log in to reply
 

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