Snapshot Summarize 599 - Minimum Index Sum of Two Lists

Original title link: force buckle


describe:

Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of favorite restaurants, each with the name of a string.

You need to help them with minimal indexing and find out their mutual favorite restaurants. If there is more than one answer, all answers are output regardless of order. You can assume the answer is always there.

Example 1:

Input: list1 = ["Shogun", "Tapioca Express", "Burger King", "KFC"], list2 = ["Piatti", "The Grill at Torrey Pines", "Hungry Hunter Steakhouse", "Shogun"]
Output : ["Shogun"]
Explanation: The only restaurant they all love in common is "Shogun".
Example 2:

Input: list1 = ["Shogun", "Tapioca Express", "Burger King", "KFC"], list2 = ["KFC", "Shogun", "Burger King"]
Output: ["Shogun"]
Explanation: They The common favorite restaurant with the smallest index sum is "Shogun", which has the smallest index sum of 1 (0+1).
 

hint:

1 <= list1.length, list2.length <= 1000
1 <= list1[i].length, list2[i].length <= 30 
list1[i] and list2[i] consist of spaces ' ' and English letters.
All strings of list1 are unique.
All strings in list2 are unique.

Source: LeetCode
Link: https://leetcode-cn.com/problems/minimum-index-sum-of-two-lists The
copyright belongs to Leetcode.com. For commercial reprints, please contact the official authorization, and for non-commercial reprints, please indicate the source.

Problem solving ideas:

* Problem solving ideas:
* Typical double-layer for loop search, one layer is converted to map to improve search efficiency. The time complexity is reduced from O(N2) to O(N).

Code:

public String[] findRestaurant(String[] list1, String[] list2) {
        Map<String, Integer> map = new HashMap<>();
        for (int i = 0; i < list1.length; i++) {
            String key1 = list1[i];
            map.put(key1, i);
        }
        int minValue = Integer.MAX_VALUE;
        List<String> list = new ArrayList<>();
        for (int i = 0; i < list2.length; i++) {
            String key2 = list2[i];
            Integer integer = map.get(key2);
            if (integer == null) {
                continue;
            }
            if (i + integer < minValue) {
                minValue = i + integer;
                list.clear();
                list.add(key2);
                continue;
            }
            if (i + integer == minValue) {
                list.add(key2);
            }
        }
        return list.toArray(new String[]{});
    }

Guess you like

Origin blog.csdn.net/AA5279AA/article/details/123473872