Go语言程序:查找两个数组的公共元素
在本教程中,我们将学习编写一个Go语言程序来查找两个数组中的公共元素。本文将介绍两个程序。第一个程序将使用字符串数组,第二个程序将使用整数数组。
方法一:使用Append()函数
以下代码演示了如何使用Go编程语言中的外部函数在两个不同的字符串数组中查找公共元素。我们将创建的函数将这两个数组作为参数,并返回包含这两个数组中公共元素的最终数组。
算法
步骤1 − 导入fmt包。
步骤2 − 定义一个名为intersection()的函数,该函数接受两个数组作为参数,并将结果数组作为函数的输出返回。
步骤3 − 创建一个名为out的空字符串数组和一个名为bucket的map。
步骤4 − 使用for循环迭代这两个数组,并检查一个数组的当前元素是否等于另一个数组的元素。
步骤5 − 重复上述过程,直到检查完所有数组,然后返回最终值。
步骤6 − 开始main()函数。
步骤7 − 初始化两个字符串数组,并将值存储到它们中,然后在屏幕上打印这两个数组。
步骤8 − 通过将这两个数组作为参数传递给intersection()函数来调用它,并将最终结果存储在另一个变量中。
步骤9 − 此变量包含具有公共元素的数组。
步骤10 − 使用fmt.Println()函数在屏幕上打印结果。
示例
使用外部函数查找两个字符串数组中公共元素的Go语言程序
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]
方法二:使用映射方法
以下代码演示了如何使用Go编程语言中的外部函数在两个不同的整数数组中查找公共元素。我们将创建的函数将这两个数组作为参数,并返回包含这两个数组中公共元素的最终数组。
算法
步骤1 − 导入fmt包。
步骤2 − 定义一个名为intersection()的函数,该函数接受两个数组作为参数,并将结果数组作为函数的输出返回。
步骤3 − 创建一个名为m的map,其键为整数,值为布尔值。
步骤4 − 使用for循环迭代数组并将它的值存储到map中。
步骤5 − 现在,使用另一个for循环迭代第二个数组,如果数组的当前元素等于map中的元素,则将此元素存储到一个新数组中。
步骤6 − 重复上述过程,直到检查完所有数组,然后返回最终数组。
步骤7 − 开始main()函数。
步骤8 − 初始化两个整数数组,并将值存储到它们中,然后在屏幕上打印这两个数组。
步骤9 − 通过将这两个数组作为参数传递给intersection()函数来调用它,并将获得的最终结果存储在另一个变量中。
步骤10 − 此变量包含具有公共元素的数组。
步骤11 − 使用fmt.Println()函数在屏幕上打印结果。
示例
使用外部函数查找两个整数数组中公共元素的Go语言程序
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语言程序,用于查找两个数组的公共元素以及示例。我们在这个程序中编写了两个程序。第一个程序使用字符串数组,而第二个程序使用整数数组来实现结果。
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP