2 回答

TA貢獻(xiàn)1803條經(jīng)驗(yàn) 獲得超3個(gè)贊
對(duì)于例如:
package main
import "fmt"
func Max(x, y int) int {
if x > y {
return x
}
return y
}
func Intersect(as, bs []string) []string {
i := make([]string, 0, Max(len(as), len(bs)))
for _, a := range as {
for _, b := range bs {
if a == b {
i = append(i, a)
}
}
}
return i
}
func main() {
MAP1 := map[string][]string{
"User": []string{"11", "33"},
"Type": []string{"A"},
}
MAP2 := map[string][]string{
"User": []string{"11", "17"},
"Type": []string{"B"},
}
MAP3 := make(map[string][]string)
for k, _ := range MAP1 {
MAP3[k] = Intersect(MAP1[k], MAP2[k])
}
fmt.Println(MAP3) // MAP3 contains commonalities between MAP1 and MAP2
}
請(qǐng)注意,此解決方案沒(méi)有利用任何潛在的性能優(yōu)化(例如假設(shè)字符串?dāng)?shù)組將以某種方式排序,或者其他方式),因此具有 O(m ? n 2 )的運(yùn)行時(shí)性能,其中:
m 是映射中的鍵數(shù)(假設(shè)兩個(gè)映射相同)
n 是每個(gè)字符串切片中的元素?cái)?shù)(假設(shè)兩個(gè)對(duì)應(yīng)的映射條目都相同)
這是好的,但不是很好。

TA貢獻(xiàn)1772條經(jīng)驗(yàn) 獲得超5個(gè)贊
您檢查這兩個(gè)地圖之間的交集的基數(shù)是否大于 0。
參見(jiàn)例如set.goIntersect in deckarep/golang-set。
// Returns a new set containing only the elements
// that exist only in both sets.
//
// Note that the argument to Intersect
// must be of the same type as the receiver
// of the method. Otherwise, Intersect will
// panic.
Intersect(other Set) Set
- 2 回答
- 0 關(guān)注
- 242 瀏覽
添加回答
舉報(bào)