Leetcode Note: Go - Minimum Inex Sum of Two Lists
Minimum Index Sum of Two Lists - LeetCode
https://leetcode.com/problems/minimum-index-sum-of-two-lists/
- Go 言語で取り組んだメモ
所感
- 2つ の string 配列で重複する要素を string 配列で return する
回答
Minimum Index Sum of Two Lists - LeetCode
https://leetcode.com/problems/minimum-index-sum-of-two-lists/solution/
Golang using map - LeetCode Discuss
https://leetcode.com/problems/minimum-index-sum-of-two-lists/discuss/283853/Golang-using-map
func findRestaurant(list1 []string, list2 []string) []string {
m := map[string]int{}
for index, val := range list1 {
m[val] = index
}
var res []string
var sum *int
for index1, val := range list2 {
var index2 int
var ok bool
if index2, ok = m[val]; !ok {
continue
}
sumIndex := index1 + index2
if sum == nil || *sum == sumIndex {
sum = &sumIndex
res = append(res, val)
} else if sumIndex < *sum {
sum = &sumIndex
res = []string{val}
}
}
return res
}
- map で重複を管理して return する