題目
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:
- The length of both lists will be in the range of [1, 1000].
- The length of strings in both lists will be in the range of [1, 30].
- The index is starting from 0 to the list length minus 1.
- No duplicates in both lists.
解題思路
- 將list1中的元素放入map中,值是該元素在list1中的index
- 遍歷list2中的元素elem,在map中如果不存在elem,則continue,如果存在,則計算兩個元素分別在連個list中的index的和
- 將這個和跟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
}