java map solution


  • 0
    U
    public class Solution {
        public String[] findRestaurant(String[] list1, String[] list2) {
            Map<String, Integer> map = new HashMap<>();
            for(int i=0; i<list1.length; i++){
                map.put(list1[i], i);
            }
            
            List<String> result = new ArrayList<>();
            Map<String, Integer> map2 = new HashMap<>();
            int min =Integer.MAX_VALUE;
            for(int i=0; i<list2.length; i++){
                if(map.containsKey(list2[i])){
                    map2.put(list2[i], map.get(list2[i])+i);
                    if(min>=(map.get(list2[i])+i)){
                        min = map.get(list2[i])+i;
                    }
                }
            }
            
            for(String s : map2.keySet()){
                if(map2.get(s)==min) result.add(s);
            }
            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.