2 回答
TA贡献1808条经验 获得超4个赞
从长度为零开始,并在附加元素时加一。例如,
package main
import "fmt"
func MergeArrays(a1, a2 []string) []string {
m := make([]string, 0, len(a1)+len(a2))
k := make(map[string]bool, len(a1)+len(a2))
for _, aa := range [][]string{a1, a2} {
for _, s := range aa {
if !k[s] {
m = append(m, s)
k[s] = true
}
}
}
return m
}
func main() {
a1 := []string{"a", "b"}
a2 := []string{"c", "d", "a"}
m := MergeArrays(a1, a2)
fmt.Println(len(m), m)
}
输出:
4 [a b c d]
TA贡献1876条经验 获得超7个赞
它们是切片,而不是数组,这是解决您的用例的示例:
package main
import "fmt"
func MergeStringSlices(str1, str2 []string) []string {
m := make([]string, len(str1), len(str1)+len(str2))
copy(m, str1)
already_seen:
for _, s := range str2 {
for _, t := range m {
if s == t {
continue already_seen
}
}
m = append(m, s)
}
return m
}
func main() {
str1 := []string{"a", "b"}
str2 := []string{"c", "d", "a"}
fmt.Printf("%#v\n", MergeStringSlices(str1, str2))
}
- 2 回答
- 0 关注
- 244 浏览
添加回答
举报