2 回答

TA贡献1798条经验 获得超7个赞
拥有不唯一的列表并不妨碍您使用地图;您可以执行如下操作(游乐场):
package main
import (
"fmt"
)
func main() {
type structA struct {
name string
otherfield int
}
type structB struct {
name string
differentField bool
}
aSlice := []structA{
{name: "foo", otherfield: 1},
{name: "foo", otherfield: 2},
{name: "unique", otherfield: 3},
{name: "one", otherfield: 4},
}
bSlice := []structB{
{name: "foo", differentField: true},
{name: "foo", differentField: false},
{name: "noIntersection", differentField: true},
{name: "one", differentField: false},
}
inA := make(map[string][]interface{})
for _, a := range aSlice {
inA[a.name] = append(inA[a.name], a)
}
intersect := make(map[string][]interface{})
for _, b := range bSlice {
if _, ok := intersect[b.name]; ok {
intersect[b.name] = append(intersect[b.name], b)
continue
}
if a, ok := inA[b.name]; ok {
intersect[b.name] = append(a, b)
continue
}
}
fmt.Println(intersect)
}

TA贡献1810条经验 获得超5个赞
我想你可以尝试在戈朗使用地图。平均复杂度时间是 O(n),因为 golang 中的映射基于哈希表。示例代码:
aMap := make(map[string][]*structA)
for _,a := range aList {
aMap[a.name] = append(aMap[a.name], a)
}
bMap := make(map[string][]*structB)
for _,b := range bList {
bMap[b.name] = append(bMap[b.name], b)
}
//get an intersection of aList and bList
itersections := make([]*structB, 0, len(aList))
for k,v := range aMap {
if b, ok := bMap[k];ok {
itersections = append(intersections, b...)
}
}
- 2 回答
- 0 关注
- 140 浏览
添加回答
举报