Golang 找到两个数组中的公共元素
在本教程中,我们将学习编写一个使用 Golang 语言的程序来查找两个数组中的公共元素。本文将编写两个程序。在第一个程序中,我们将使用字符串数组,而在第二个程序中,我们将使用整数数组。
方法 1:使用 Append() 函数
以下代码演示了如何使用外部函数在 Golang 编程语言中找到两个不同字符串数组中的公共元素。我们将创建的函数将接受这两个数组作为参数,并返回包含两个数组中的公共元素的最终数组。
步骤
步骤 1 - 导入 fmt 包。
步骤 2 - 定义一个名为 intersection() 的函数,该函数接受两个数组作为参数,并将结果数组作为函数的输出。
步骤 3 - 创建一个名为 out 的空字符串数组和一个名为 bucket 的 map。
步骤 4 - 使用 for 循环来遍历两个数组,并检查一个数组的当前元素是否等于另一个数组的元素。
步骤 5 - 重复上述过程直到检查完整个数组,并返回最终值。
步骤 6 - 开始 main() 函数。
步骤 7 - 初始化两个字符串数组,并将值存储在它们中,将这两个数组打印在屏幕上。
步骤 8 - 通过将这两个数组作为参数传递给 intersection() 函数来调用该函数,并将最终结果存储在另一个变量中。
步骤 9 - 这个变量包含有公共元素的数组。
步骤 10 - 使用 fmt.Println() 函数在屏幕上打印结果。
示例
Golang 程序,使用外部函数查找两个字符串数组中的公共元素
package main
import "fmt"
// function to get common elements 2. Golang Program to find the common elements from two arrays
func intersection(arr1, arr2 []string) []string {
out := []string{}
bucket := map[string]bool{}
for _, i := range arr1 {
for _, j := range arr2 {
if i == j && !bucket[i] {
out = append(out, i)
bucket[i] = true
}
}
}
return out
}
func main() {
arr1 := []string{"apple", "mango", "banana", "papaya"}
fmt.Println("The first array entered is:", arr1)
arr2 := []string{"cherry", "papaya", "mango"}
fmt.Println("The second array entered is:", arr2)
result := intersection(arr1, arr2)
fmt.Println()
fmt.Println("The common elements of the above two arrays are:", result)
}
输出
The first array entered is: [apple mango banana papaya]
The second array entered is: [cherry papaya mango]
The common elements of the above two arrays are: [mango papaya]
方法2:使用映射方法
以下代码示例了如何使用go编程语言中的外部函数找到两个不同整数数组中的公共元素。我们将创建的函数接受这两个数组作为参数,并返回包含两个数组中的公共元素的最终数组。
步骤
步骤1 - 导入fmt包。
步骤2 - 定义一个名为intersection()的函数,它接受两个数组作为参数,并将结果数组作为函数的输出返回。
步骤3 - 创建一个名为m的映射,键为整数,值为布尔型。
步骤4 - 使用for循环遍历数组并将其值存储到映射中。
步骤5 - 现在,使用另一个for循环遍历第二个数组,如果数组的当前元素等于映射中的元素,则将该元素存储在一个新数组中。
步骤6 - 重复上述过程直到检查完整个数组,并返回最终数组。
步骤7 - 开始main()函数。
步骤8 - 初始化两个整数数组并将值存储在它们中,在屏幕上打印这两个数组。
步骤9 - 通过将这两个数组作为参数传递给intersection()函数来调用函数,并将得到的最终结果存储在一个不同的变量中。
步骤10 - 此变量包含具有公共元素的数组。
步骤11 - 使用fmt.Println()函数将结果打印到屏幕上。
示例
使用外部函数查找两个整数数组中的公共元素的Golang程序。
package main
import (
"fmt"
)
// creating an Intersection function
func intersection(a, b []int) (c []int) {
m := make(map[int]bool)
for _, item := range a {
// storing value to the map
m[item] = true
}
for _, item := range b {
if _, ok := m[item]; ok {
c = append(c, item)
}
}
return c
}
func main() {
arr1 := []int{10, 25, 34, 56, 69}
fmt.Println("The first array entered is:", arr1)
arr2 := []int{34, 69, 54, 44}
fmt.Println("The second array entered is:", arr2)
fmt.Println()
result := intersection(arr1, arr2)
fmt.Println("The common elements of the above two arrays are:", result)
}
输出
The first array entered is: [10 25 34 56 69]
The second array entered is: [34 69 54 44]
The common elements of the above two arrays are: [34 69]
结论
我们已经成功地编译和执行了一个Go语言程序,用于查找两个数组的共同元素,并提供了示例。我们在这个过程中编写了两个程序。第一个程序使用字符串数组,而第二个程序使用整数数组来实现结果。