使用哈希表在 Golang 中查找重复数字。

huangapple go评论87阅读模式
英文:

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
	}
}

huangapple
  • 本文由 发表于 2021年8月9日 14:08:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/68707512.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定