3 回答

TA貢獻(xiàn)1875條經(jīng)驗 獲得超3個贊
你幾乎明白了。請注意是否a在B. 如果a在 中找不到B,則添加a到結(jié)果中。
func main() {
A := []string{"a", "b", "c", "d"}
B := []string{"a", "b"}
var result []string
for _, a := range A {
found := false
for _, b := range B {
if a == b {
found = true
break
}
}
if !found {
result = append(result, a)
}
}
fmt.Println(result)
}

TA貢獻(xiàn)1735條經(jīng)驗 獲得超5個贊
func main() {
A := []string{"a", "b", "c", "d"}
B := []string{"a", "b"}
var outterLoop, innerLoop []string
if len(A) > len(B) {
outterLoop = A
innerLoop = B
} else {
outterLoop = B
innerLoop = A
}
temp := []string{}
for _, b := range outterLoop {
found := false
for _, a := range innerLoop {
if a == b {
found = true
}
}
if !found {
temp = append(temp, b)
}
}
for _, t := range temp {
println(t)
}
}

TA貢獻(xiàn)1828條經(jīng)驗 獲得超4個贊
package main
import "fmt"
func find(a, b []string) []string {
bm := make(map[string]struct{}, len(b))
ok := false
for i := range b {
if _, ok = bm[b[i]]; !ok {
bm[b[i]] = struct{}{}
}
}
res := make([]string, 0)
for i := range a {
if _, ok = bm[a[i]]; !ok {
res = append(res, a[i])
}
}
return res
}
func main() {
a := []string{"a", "b", "c", "d"}
b := []string{"a", "b"}
t := find(a, b)
fmt.Println(t)
}
- 3 回答
- 0 關(guān)注
- 128 瀏覽
添加回答
舉報