[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,如果存在,則計(jì)算兩個元素分別在連個list中的index的和
  3. 將這個和跟minIndex比較,如果比minIndex小,則結(jié)果數(shù)組置為該元素組成的數(shù)組;如果和minIndex相等,則說明有Index和相等的餐廳,將改元素append到結(jié)果數(shù)組上

注意
兩個數(shù)組的index范圍[1, 1000], 可以將minIndex設(shè)為大于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
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容