LeetCode 599: Minimum Index Sum of Two Lists

Keywords: Java Python

Title:

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

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 index and find their favorite restaurants with the least amount. If there is more than one answer, all the answers are output regardless of the order. You can assume that there is always an answer.

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.

Example 1:

Input:
["Shogun", "Tapioca Express", "Burger King", "KFC"]
["Piatti", "The Grill at Torrey Pines", "Hungry Hunter Steakhouse", "Shogun"]
Output: ["Shogun"]
Explanation: their only favorite restaurant is "Shogun".

Example 2:

Input:
["Shogun", "Tapioca Express", "Burger King", "KFC"]
["KFC", "Shogun", "Burger King"]
Output: ["Shogun"]
Explanation: their favorite restaurant with the smallest index sum is "Shogun", which has the smallest index and 1 (0 + 1).

Tips:

  1. The length range of both lists is within [1, 1000].
  2. The length of strings in both lists will be in the range of [1, 30].
  3. The subscript starts at 0, and the length to the list decreases by 1.
  4. Neither list has duplicate elements.

Note:

  1. The length of both lists will be in the range of [1, 1000].
  2. The length of strings in both lists will be in the range of [1, 30].
  3. The index is starting from 0 to the list length minus 1.
  4. No duplicates in both lists.

Solutions:

Two string arrays, find the repeated elements, return their index and the smallest target array. The easiest solution to think of is to use hash map to solve the problem. Key stores each element Value of its array, and Value stores its subscript index. The first traversal adds one of the arrays to the hash map, and the second traverses to find the target element. A minimum index sum needs to be maintained to ensure that the target index sum of the query is the minimum.

Hash table solution:

Java:

class Solution {
    public String[] findRestaurant(String[] list1, String[] list2) {
        Map<String, Integer> map = new HashMap<>();//Build hash map
        for (int i = 0; i < list1.length; i++)//Mapping an array by first traversal
            map.put(list1[i], i);
        List<String> res = new ArrayList<>();//Target array to be returned
        int sum = Integer.MAX_VALUE;//Sum is the minimum index sum that currently meets the condition
        for (int i = 0; i < list2.length; i++) {//Second traversal to find the target element
            if (map.containsKey(list2[i])) {
                int tmp = i + map.get(list2[i]);//Current index and
                if (tmp < sum) {//If the current index and smaller
                    res.clear();//Clear target array
                    res.add(list2[i]);//Add this element
                    sum = tmp;// Refresh minimum index and
                } else if (tmp == sum)//If index and are equal
                    res.add(list2[i]);//Add elements only
            }
        }
        return res.toArray(new String[res.size()]);//Convert to string array
    }
}

Python:

class Solution:
    def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]:
        hash_map = dict()# Build hash map
        for i, s in enumerate(list1):# Mapping an array by first traversal
            hash_map[s] = i
        min_sum = 2001# The minimum index sum that currently meets the condition
        res = list()# Target array to be returned
        for i, s in enumerate(list2):# The second enumeration traverses to find the target element
            if s in hash_map:
                tmp = i+hash_map[s]# Current index and
                if tmp < min_sum:# If the current index and smaller
                    res.clear()# Clear target array
                    res.append(s)# Add this element
                    min_sum = tmp# Refresh minimum index and
                elif tmp == min_sum:# If index and are equal
                    res.append(s)# Add elements only
        return res

Operation index solution:

This solution is ingenious, though inefficient. The following explanation is excerpted from LeetCode, which can be used as a reference extension idea:

The other can traverse different sum sum (subscript and), and judge whether there are strings in list1 and list2, and the subscript and sum are sum.

Now we know that the sum of subscripts ranges from 0 to m + n - 1. Here m and N are the length of list1 and list2 respectively. Now we can enumerate sum in ascending order. For each sum, we traverse list1, assuming the current subscript is i. in order to get the subscript and sum, the subscript j in list2 is sum − i. In this way, we do not need to traverse list2, but can directly calculate the corresponding subscript in list2.

For each sum, we traverse all subscripts of list1. Once there is a string match between list1 and list2, we put the matching string into a res list.

We do the same process for all the values in the sum ascending array. After traversing list1 for each sum, we check whether the res list is empty. If it is empty, we continue to traverse the next sum array. If it is not empty, the current res is the array of the minimum subscript sum. This is because we traverse sum in ascending order, so the first list we find is the result list.

Link! https://leetcode-cn.com/probl...

Java:

class Solution {
    public String[] findRestaurant(String[] list1, String[] list2) {
        List<String> res = new ArrayList<>();
        for (int sum = 0; sum < list1.length + list2.length - 1; sum++) {
            for (int i = 0; i <= sum; i++) {
                if (i < list1.length && sum - i < list2.length && list1[i].equals(list2[sum - i]))
                    res.add(list1[i]);
            }
            if (res.size() > 0) break;//Once the minimum index and sequence are found, the traversal is finished directly, because sum is incremental, and the index sum will be larger.
        }
        return res.toArray(new String[res.size()]);
    }
}

Python

class Solution:
    def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]:
        res = list()
        list1_size, list2_size = len(list1), len(list2)
        for min_sum in range(list1_size+list2_size-1):
            for i in range(min_sum+1):
                if i < list1_size and min_sum-i < list2_size and list1[i] == list2[min_sum-i]:
                    res.append(list1[i])
            if len(res) > 0:# Once the minimum index and sequence are found, the traversal is finished directly, because sum is incremental, and the index sum will be larger.
                break
        return res

Welcome to wechat. Xin Gong. Nickname: love to write Bug

Posted by kumaran on Thu, 24 Oct 2019 19:05:18 -0700