亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何更快地獲得2個列表之間的交集

如何更快地獲得2個列表之間的交集

Go
慕桂英3389331 2022-10-04 16:24:00
我有2個列表,一個列表元素類型是結構A,另一個列表元素類型是結構B,結構A和結構B之間有公共字段。如何獲取在 2 個列表之間具有相同內容的交集元素,并使用 golang 避免 o(n^2) 時間復雜度。string namenametype structA struct {   name string   ....}type structB struct {   name string   ..}注意:每個列表中的字段不是唯一的,因此轉換地圖的方式不是解決方案name
查看完整描述

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)

}


查看完整回答
反對 回復 2022-10-04
?
森欄

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...)

    }

}


查看完整回答
反對 回復 2022-10-04
  • 2 回答
  • 0 關注
  • 101 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號