英文:
How to finding result of intercept of two slices in golang
问题
有两个字符串切片,我想在Golang中找到这两个切片的交集结果,并且希望找到最佳解决方案,而不是遍历每个切片。
first_slice := []string{"F8-E7-1E-14-AE-00", "F8-E7-1E-14-D0-30", "84-18-3A-2F-05-E0","84-18-3A-2F-05-E8"}
second_slice := []string{"F8-E7-1E-14-D0-30", "84-18-3A-2F-05-E8","F8-E7-1E-54-AE-08"}
输出:
result_slice := []string{"F8-E7-1E-14-D0-30", "84-18-3A-2F-05-E8"}
我已经尝试了以下方法,但对于大数据集来说并不是最佳方法:
var result_slice *[]string
for _, i := range first_slice {
for _, x := range second_slice {
if i == x {
&result_slice.append(i)
}
}
}
如果能给我一个更好的解决方案,我将不胜感激。
英文:
There is two slices in string type.I want to finding intercept result in set from the two slices in golang.I want to find the best solution rather than iterating each slice.
first_slice := []string{"F8-E7-1E-14-AE-00", "F8-E7-1E-14-D0-30", "84-18-3A-2F-05-E0","84-18-3A-2F-05-E8" }
second_slice := []string{"F8-E7-1E-14-D0-30", "84-18-3A-2F-05-E8","F8-E7-1E-54-AE-08"}
Output:
result_slice := []string{"F8-E7-1E-14-D0-30", "84-18-3A-2F-05-E8"}
I have use following approaches but it is not best approaches for large data set.
var result_slice *[]string
for _, i := range first_slice {
for _, x := range second_slice {
if i == x {
&result_slice.append(i)
}
}
}
Appreciate if give me good solution that.
答案1
得分: 2
第一部分:
firstSlice := []string{"F8-E7-1E-14-AE-00", "F8-E7-1E-14-D0-30",
"84-18-3A-2F-05-E0", "84-18-3A-2F-05-E8"}
secondSlice := []string{"F8-E7-1E-14-D0-30", "84-18-3A-2F-05-E8",
"F8-E7-1E-54-AE-08"}
resultSlice := []string{}
checkMap := map[string]struct{}{}
for _, addr := range firstSlice {
checkMap[addr] = struct{}{}
}
for _, addr := range secondSlice {
if _, ok := checkMap[addr]; ok {
resultSlice = append(resultSlice, addr)
}
}
fmt.Println(resultSlice)
输出结果是你想要的。
空结构在内存中不占用空间。
此外,在Go语言中,始终使用驼峰命名法。
英文:
firstSlice := []string{"F8-E7-1E-14-AE-00", "F8-E7-1E-14-D0-30",
"84-18-3A-2F-05-E0", "84-18-3A-2F-05-E8"}
secondSlice := []string{"F8-E7-1E-14-D0-30", "84-18-3A-2F-05-E8",
"F8-E7-1E-54-AE-08"}
resultSlice := []string{}
checkMap := map[string]struct{}{}
for _, addr := range firstSlice {
checkMap[addr] = struct{}{}
}
for _, addr := range secondSlice {
if _, ok := checkMap[addr]; ok {
resultSlice = append(resultSlice, addr)
}
}
fmt.Println(resultSlice)
The output is what you want.
An empty struct takes no space in monery
What's more, always use camel in golang.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论