Go语言程序查找数组公共元素
在本教程中,我们将学习如何编写一个Go语言程序来查找两个数组中的公共元素。
使用用户自定义函数查找公共数组元素
以下代码演示了如何查找两个不同字符串数组中的公共元素。
算法
步骤1 − 导入fmt包。
步骤2 − 定义一个名为intersection()的函数,该函数接受两个数组作为参数,并将结果数组作为函数输出返回。
步骤3 − 创建一个空的字符串数组out和一个名为bucket的映射。
步骤4 − 使用for循环迭代两个数组,并检查一个数组的当前元素是否等于另一个数组的元素。
步骤5 − 如果条件为真,则需要将该元素存储在上面创建的空数组中,并翻转bucket映射的布尔值。
步骤6 − 重复上述过程,直到检查完所有数组,然后返回最终值。
步骤7 − 启动main()函数。
步骤8 − 初始化两个字符串数组并向其中存储值,然后在屏幕上打印这两个数组。
步骤9 − 通过将两个数组作为参数传递给函数来调用intersection()函数,并将最终结果存储在另一个变量中。
步骤10 − 此变量包含具有公共元素的数组。
步骤11 − 使用fmt.Println()函数在屏幕上打印结果。
示例
package main
import "fmt"
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{"one", "two", "three", "four"}
fmt.Println("The first array entered is:", arr1)
arr2 := []string{"two", "four"}
fmt.Println("The second array entered is:", arr2)
result := intersection(arr1, arr2)
fmt.Println("The common elements of the above two arrays are:", result)
}
输出
The first array entered is: [one two three four] The second array entered is: [two four] The common elements of the above two arrays are: [two four]
使用外部函数在整数数组中查找公共数组元素
在此示例中,我们将编写一个Go语言程序,使用用户自定义函数查找公共整数数组元素。
算法
步骤1 − 导入fmt包。
步骤2 − 定义一个名为intersection()的函数,该函数接受两个数组作为参数,并将结果数组作为函数输出返回。
步骤3 − 创建一个名为m的映射,其键为整数,值为布尔值。
步骤4 − 使用for循环迭代数组并将它的值存储到映射中。
步骤5 − 现在,使用另一个for循环迭代第二个数组,如果数组的当前元素等于映射中的值,则将此元素存储到新数组中。
步骤6 − 重复上述过程,直到检查完所有数组,然后返回最终数组。
步骤7 − 启动main()函数。
步骤8 − 初始化两个整数数组并向其中存储值,然后在屏幕上打印这两个数组。
步骤9 − 通过将两个数组作为参数传递给函数来调用intersection()函数,并将获得的最终结果存储在另一个变量中。
步骤10 − 此变量包含具有公共元素的数组。
步骤11 − 使用fmt.Println()函数在屏幕上打印结果。
示例
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{1, 2, 3, 4, 5}
fmt.Println("The first array entered is:", arr1)
arr2 := []int{4, 5, 6, 7}
fmt.Println("The second array entered is:", arr2)
result := intersection(arr1, arr2)
fmt.Println("The common elements of the above two arrays are:", result)
}
输出
The first array entered is: [1 2 3 4 5] The second array entered is: [4 5 6 7] The common elements of the above two arrays are: [4 5]
结论
我们已经成功编译并执行了一个Go语言程序,用于查找两个数组的公共元素以及示例。
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP