Easily Understandable Solution Java


  • 0
    A
    public String[] findRestaurant(String[] list1, String[] list2) {
            Map<String,Integer> hm = new HashMap<String,Integer>();
            Map<String,Integer> hm2 = new HashMap<String,Integer>();
            //Put in two HashMap<Name, Index>
            for (int i = 0; i < list1.length; i++)
                 hm.put(list1[i], i);
            for (int i = 0; i < list2.length; i++)
                 hm2.put(list2[i], i);
            //Find common keys in two hashmaps
            Set<String> hs = new HashSet<String>(hm.keySet());
            hs.retainAll(hm2.keySet());
            //Find minimum index
            int min = Integer.MAX_VALUE;
            for(String cmm: hs)
                min = Math.min(min, hm.get(cmm)+hm2.get(cmm));
            //Add to return list if index sum == min
            List<String> al = new ArrayList<String>();
            for(String cmm: hs){
                if((hm.get(cmm)+hm2.get(cmm))==min)        		
                    al.add(cmm);
            }
            return al.toArray(new String[al.size()]); 
        }

Log in to reply
 

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