Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of favorite restaurants represented by strings.

You need to help them find out their common interest with the least list index sum. If there is a choice tie between answers, output all of them with no order requirement. You could assume there always exists an answer.

class Solution {
    public String[] findRestaurant(String[] list1, String[] list2) {
        HashMap<String, Integer> map1 = new HashMap<String, Integer>();
        HashMap<String, Integer> map2 = new HashMap<String, Integer>();

        for(int i = 0; i < list1.length; i++) 
            map1.put(list1[i], i);
        for(int i = 0; i < list2.length; i++) 
            map2.put(list2[i], i);

        int min = Integer.MAX_VALUE;
        for(int i = 0; i < list1.length; i++) {
            if(map2.containsKey(list1[i])) {
                min = Math.min(min, i + map2.get(list1[i]));
            }
        }

        List<String> list = new ArrayList<String>();
        for(int i = 0; i < list1.length; i++) {
            if(map2.containsKey(list1[i])) {
                if(map2.get(list1[i]) + i == min) {
                    list.add(list1[i]);
                }
            }
        }

        String[] res = new String[list.size()];
        for(int i = 0; i < res.length; i++)
            res[i] = list.get(i);

        return res;
    }
}

results matching ""

    No results matching ""