英文:
findDuplicate number in golang using hashmap
问题
你好,我想询问一下关于在Go语言中查找重复元素的问题。
如果在Python中,我可以这样做:
def findDuplicate(data):
seen = []
for number in data:
if number in seen:
print(number)
seen.append(number)
print(seen)
data = [1,2,4,5,6,4]
findDuplicate(data)
# 期望输出结果为 4
在Go语言中是否有类似于Python中的if number in seen
的函数呢?
谢谢。
英文:
hi i want ask about findDuplicate in golang
if in python i can do this
def findDuplicate(data):
seen = []
for number in data:
if number in seen:
print(number)
seen.append(number)
print(seen)
data = [1,2,4,5,6,4]
findDuplicate(data)
#expected output 4
is there any similiar function in golang like "if number in seen" on python?
Thank you
答案1
得分: 3
你可以遍历数据,并在不重复时写入到一个映射(map)中。如果数据已经存在于映射中,则将其追加到重复项切片(duplicates)中。示例代码如下所示:
注意:如果有多个具有相同值的重复项,此代码将显示所有多个重复项。如果您只想看到相同的重复值一次,需要进行更改。
package main
import (
"fmt"
)
func main() {
data := []int{1,2,4,5,6,4}
findDuplicates(data)
}
func findDuplicates(data []int) {
values := make(map[int]struct{})
var duplicates []int
for _, d := range data {
if _, ok := values[d]; ok {
duplicates = append(duplicates, d)
continue
}
values[d] = struct{}{}
}
fmt.Println(duplicates) // 输出:[4]
}
在 playground 上运行。
英文:
You can iterate through your data and write to a map if it is not a duplicate. And append to duplicates slice if it is already exist in the map. Sample code is like below.
Note: if you have multiple duplicates with same value, this code is showing all multiple duplicates. If you need to see same duplicate value once, this should be changed
package main
import (
"fmt"
)
func main() {
data := []int{1,2,4,5,6,4}
findDuplicates(data)
}
func findDuplicates(data []int) {
values := make(map[int]struct{})
var duplicates []int
for _, d := range data {
if _, ok := values[d]; ok {
duplicates = append(duplicates, d)
continue
}
values[d] = struct{}{}
}
fmt.Println(duplicates) // Output: [4]
}
run with playground
答案2
得分: 1
你正在寻找maps。
示例用法:
func findDuplicate(data []int) {
uniq := map[int]bool{}
for _, i := range data {
if uniq[i] {
fmt.Printf("找到重复项 %v", i)
}
uniq[i] = true
}
}
英文:
you are looking for maps
Example usage:
func findDuplicate(data []int) {
uniq := map[int]bool{}
for _, i := range data {
if uniq[i] {
fmt.Printf("found duplicate %v", i)
}
uniq[i] = true
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论