One HashMap


  • 1
    X

    public String[] findRestaurant(String[] list1, String[] list2) {
    List<String> res = new ArrayList<>();

     Map<String, Integer> map = new HashMap<>();
     
     
     
     int tmp = Integer.MAX_VALUE;
     for(int i = 0; i < list1.length; i++){
         
         map.put(list1[i],i);
         
     }
     
     for(int i = 0; i < list2.length; i++){
         if(map.containsKey(list2[i])){
             int pre = map.get(list2[i]);
             
             if(pre + i < tmp){
                 res = new ArrayList<>();
                 res.add(list2[i]);
                 tmp = pre + i;
             }
             else if(pre + i == tmp)
                res.add(list2[i]);
         }
     }
     
     String[] r = new String[res.size()];
     
     int i = 0;
     for(String s : res){
         r[i ++] = s;
     }
     
     return r;
    }
    

    }


Log in to reply
 

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