Java easy understand-HashMap


  • 0
     public String[] findRestaurant(String[] list1, String[] list2) {
            Map<String,Integer> map1 = new HashMap<>();
            Map<String,Integer> map2 = new HashMap<>();
            for(int i=0;i<list1.length;i++){
                map1.put(list1[i],i);
            }
            for(int i=0;i<list2.length;i++){
                if(map1.containsKey(list2[i])){
                    map2.put(list2[i],i+map1.get(list2[i]));
                }
            }
            List<String> list = new ArrayList<>();
            String minKey=null;
            int minValue=Integer.MAX_VALUE;
            for(String key:map2.keySet()){
                int value = map2.get(key);
                if (value < minValue) {
                    minValue = value;
                    minKey = key;
                }
            }
            for(String key:map2.keySet()){
                int value=map2.get(key);
                if(value==minValue){
                    list.add(key);
                }
            }
            String[] ans = new String[list.size()];
            for(int i=0;i<list.size();i++) ans[i]=list.get(i);
            return ans;
            
        }
    

Log in to reply
 

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