LeetCode 599: the sum of the minimum index Minimum Index Sum two lists of Two Lists

topic:

Suppose Andy and Doris want to choose a restaurant for dinner, and they have expressed a favorite restaurant list, the name of each restaurant is represented by a string.

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 with a minimum of index and find out their common favorite restaurant . If the answer is more than one output all the answers and do not consider 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:

输入:
["Shogun", "Tapioca Express", "Burger King", "KFC"]
["Piatti", "The Grill at Torrey Pines", "Hungry Hunter Steakhouse", "Shogun"]
输出: ["Shogun"]
解释: 他们唯一共同喜爱的餐厅是“Shogun”。

Example 2:

输入:
["Shogun", "Tapioca Express", "Burger King", "KFC"]
["KFC", "Shogun", "Burger King"]
输出: ["Shogun"]
解释: 他们共同喜爱且具有最小索引和的餐厅是“Shogun”,它有最小的索引和1(0+1)。

prompt:

  1. Length two lists are [1, 1000] within.
  2. Length of the string within the two lists will be in the range [1,30] of.
  3. Index from 0 to 1 minus the length of the list.
  4. Both lists are no 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.

Problem-solving ideas:

Two string array to find recurring elements, and returns to its minimum target array index. Most likely to think the solution is to use a hash map problem-solving, Key store its value to each element of the array, Value stores its index index. The first time through will be added to the array in which a hash map, the second pass to find the target element. The need to maintain a minimum to ensure the index and query the index and the minimum target.

Hash table problem solving:

Java:

class Solution {
    public String[] findRestaurant(String[] list1, String[] list2) {
        Map<String, Integer> map = new HashMap<>();//建立哈希映射
        for (int i = 0; i < list1.length; i++)//初次遍历将一个数组建立映射关系
            map.put(list1[i], i);
        List<String> res = new ArrayList<>();//待返回的目标数组
        int sum = Integer.MAX_VALUE;//sum为当前满足条件的最小索引和
        for (int i = 0; i < list2.length; i++) {//第二次遍历查找目标元素
            if (map.containsKey(list2[i])) {
                int tmp = i + map.get(list2[i]);//当前索引和
                if (tmp < sum) {//如果当前索引和更小
                    res.clear();//清除目标数组
                    res.add(list2[i]);//添加该元素
                    sum = tmp;// 刷新最小索引和
                } else if (tmp == sum)//如果索引和相等
                    res.add(list2[i]);//只添加元素
            }
        }
        return res.toArray(new String[res.size()]);//转成 string 数组
    }
}

Python:

class Solution:
    def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]:
        hash_map = dict()# 建立哈希映射
        for i, s in enumerate(list1):# 初次遍历将一个数组建立映射关系
            hash_map[s] = i
        min_sum = 2001# 当前满足条件的最小索引和
        res = list()# 待返回的目标数组
        for i, s in enumerate(list2):# 第二次枚举遍历查找目标元素
            if s in hash_map:
                tmp = i+hash_map[s]# 当前索引和
                if tmp < min_sum:# 如果当前索引和更小
                    res.clear()# 清除目标数组
                    res.append(s)# 添加该元素
                    min_sum = tmp# 刷新最小索引和
                elif tmp == min_sum:# 如果索引和相等
                    res.append(s)# 只添加元素
        return res

Operation index problem solving:

This solution is very clever, although the efficiency is very low. The following explanation is taken from LeetCode, it can be used as a reference extension ideas:

Another may traverse different Sumsum (and subscript), and determines whether there is list1 and list2 and the subscript and the sum of each string appears.

We now know the value of the numerical sum and the subscript range from 0 to m + n - 1. Where m and n are the lengths of list1 and list2, we can now ascending enumeration sum, for each sum, we traverse list1, assumed that the current index is i, and in order to obtain the subscript sum, the index J is list2 sum-i. By such an approach, we do not need to traverse list2, but may be obtained directly by calculation corresponding to the index in list2.

For each sum, we go through all indices list1, once a matching string list1 and list2 in, put the match into a string res list.

We do the same procedure on the sum of all values ​​in the array in ascending order, for each sum traversed again after list1, we check whether res list is empty. If it is empty, we continue to traverse the next sum array. If not empty, the current index is the smallest and res array. This is because we traverse the sum of the order is ascending, so the list is the first to find the list of results.

! - Links: https://leetcode-cn.com/problems/minimum-index-sum-of-two-lists/solution/liang-ge-lie-biao-de-zui-xiao-suo-yin-zong -he-by-l / -

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;//一旦找到最小索引和序列直接结束遍历,因为sum是递增的,之后得到的索引和一定更大
        }
        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:# 一旦找到最小索引和序列直接结束遍历,因为sum是递增的,之后得到的索引和一定更大
                break
        return res

Micro welcome attention. Letter public. Public number: Write Love Bug
I love to write Bug.png

Guess you like

Origin www.cnblogs.com/zhangzhe532/p/11735913.html