[LeetCode By Go 40]599. Minimum Index Sum of Two Lists

题目

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.

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 both like is “Shogun”.

Example 2:

Input:
[“Shogun”, “Tapioca Express”, “Burger King”, “KFC”]
[“KFC”, “Shogun”, “Burger King”]
Output: [“Shogun”]
Explanation: The restaurant they both like and have the least index sum is “Shogun” with index sum 1 (0+1).

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.

解题思路

  1. 将list1中的元素放入map中,值是该元素在list1中的index
  2. 遍历list2中的元素elem,在map中如果不存在elem,则continue,如果存在,则计算两个元素分别在连个list中的index的和
  3. 将这个和跟minIndex比较,如果比minIndex小,则结果数组置为该元素组成的数组;如果和minIndex相等,则说明有Index和相等的餐厅,将改元素append到结果数组上

注意
两个数组的index范围[1, 1000], 可以将minIndex设为大于2000的值

代码

func findRestaurant(list1 []string, list2 []string) []string {
    var restaurants []string

    var restaurantMap1 map[string]int
    restaurantMap1 = make(map[string]int)

    len1 := len(list1)
    for i := 0; i < len1; i++ {
        restaurantMap1[list1[i]] = i
    }

    minIndex := 3000 // > 2000

    len2 := len(list2)
    for i := 0; i < len2; i++ {
        tmp, ok := restaurantMap1[list2[i]]
        if !ok {
            continue
        } else {
            if minIndex > tmp + i {
                minIndex = tmp + i
                restaurants = []string{list2[i]}
            } else if minIndex == tmp + i {
                restaurants = append(restaurants, list2[i])
            }

        }
    }


    return restaurants
}
    原文作者:miltonsun
    原文地址: https://www.jianshu.com/p/c0d919e1395e
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞