LeetCode-599. The minimum index sum of the two lists

Title description:

Suppose Andy and Doris want to choose a restaurant for dinner, and they both have a list of favorite restaurants, and the name of each restaurant is represented by a string.
You need to help them use the least index and find their favorite restaurants. If there is more than one answer, all answers are output regardless of order. You can assume that there is always an answer.

prompt:

  • The length of the two lists is in the range of [1, 1000].
  • The length of the strings in the two lists will be in the range of [1, 30].
  • The subscript starts from 0 and goes to the length of the list minus 1.
  • There are no duplicate elements in both lists.

Example 1:
Input:

  • [“Shogun”, “Tapioca Express”, “Burger King”, “KFC”]
  • [“Piatti”, “The Grill at Torrey Pines”, “Hungry Hunter Steakhouse”, “Shogun”]

Output: ["Shogun"]
Explanation: The only restaurant they love in common is "Shogun".

Example 2:
Input:

  • [“Shogun”, “Tapioca Express”, “Burger King”, “KFC”]
  • [“KFC”, “Shogun”, “Burger King”]

Output: ["Shogun"]
Explanation: The restaurant they both love and has the smallest index sum is "Shogun", which has the smallest index and 1(0+1).

code show as below:

class Solution {
    
    
    public String[] findRestaurant(String[] list1, String[] list2) {
    
    
        ArrayList<String> strings = new ArrayList<>();
        HashMap<String, Integer> map = new HashMap<>();
        HashMap<String, Integer> map1 = new HashMap<>();
        int n = list1.length;
        for (int i = 0; i < n; i++) {
    
    
            map.put(list1[i], i);
        }
        int m = list2.length;
        for (int j = 0; j < m; j++) {
    
    if (map.containsKey(list2[j])) {
    
    
                map1.put(list2[j], map.get(list2[j]) + j);
            }
        }
        int ans = Integer.MAX_VALUE;
        for (var entry : map1.entrySet()) {
    
    
            if (entry.getValue() < ans) {
    
    
                strings.clear();
                strings.add(entry.getKey());
            } else if (entry.getValue() == ans) {
    
    
                strings.add(entry.getKey());
            }
            ans = Math.min(entry.getValue(), ans);
        }
        return strings.toArray(new String[strings.size()]);
    }
}

Results of the:
Insert picture description here

Guess you like

Origin blog.csdn.net/FYPPPP/article/details/114299811