Java hashmap and stack solution.


  • 0
    G
    public String[] findRestaurant(String[] list1, String[] list2) {
        Map<String, Integer> map = new HashMap<>();
        Stack<String> res = new Stack<>();
        for (int i = 0; i < list1.length; i++) {
          map.put(list1[i], i);
        }
        int min = -1;
        for (int i = 0; i < list2.length; i++) {
          if (map.containsKey(list2[i])) {
            int sum = i + map.get(list2[i]);
            if (min > sum) {
              res.pop();
            }
            if (res.isEmpty() || min >= sum) {
              res.add(list2[i]);
              min = sum;
            }
          }
        }
        return res.toArray(new String[res.size()]);
      }
    

Log in to reply
 

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