EASY understand JAVA solution, find the minimum index sum first.


  • 0
    B

    The key question is to find the minimum sum of index. My approach is like this: we could find it with one loop and use the minimum sum to find all the pairs of index which satisfies the minimum sum. That is an easy understand approach. Please see the code below:

    public class Solution {
        public String[] findRestaurant(String[] list1, String[] list2) {
            List<String> list = new LinkedList<>();
            Map<String, Integer> map = new HashMap<>();
            int min = Integer.MAX_VALUE;
    
            for (int i = 0; i < list1.length; i++) {
                map.put(list1[i], i);
            }
            //Find the minimum index sum;
            for (int i = 0; i < list2.length; i++) {
                if (map.containsKey(list2[i])) {
                    min = Math.min(min, i + map.get(list2[i]));
                }
            }
            //Find the pair of index which satisfies the index sum;
            for (int i = 0; i < list2.length; i++) {
                if (map.containsKey(list2[i]) && i + map.get(list2[i]) == min) {
                    list.add(list2[i]);
                }
            }
            return list.toArray(new String[0]);
        }
    }
    

Log in to reply
 

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