Easy Understanding Java Solution with Explanation


  • 1
    X
    public class Solution {
        public String[] findRestaurant(String[] list1, String[] list2) {
            Map<String, Integer> map = new HashMap<>();
            List<String> res = new LinkedList<>();
            int indexSum = Integer.MAX_VALUE;
            
            for(int i = 0; i < list1.length; i++) {
                map.put(list1[i], i);
            }
            for(int i = 0; i < list2.length; i++) {
                // the same restaurant is existing && sum of the indexs are not greater than previous sum.
                if(map.containsKey(list2[i]) && indexSum >= map.get(list2[i]) + i) {  
                    // if sum is less than previous sum, get rid of the previous sum, create a new list.
                    if(indexSum > map.get(list2[i]) + i) {  
                        res =  new LinkedList<>();
                        indexSum = map.get(list2[i]) + i;
                    }
                    // add the same restaurant's name anyway.
                    res.add(list2[i]);
                }
            }
            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.