Golang程序 寻找数组公共元素

Golang程序 寻找数组公共元素

在本教程中,我们将看到写一个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循环遍历数组并将其值存储到map中。

第5步 - 现在,使用另一个for循环遍历第二个数组,如果数组的当前元素等于map,则将该元素存储在一个新的数组中。

第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语言程序,以寻找两个数组的共同元素,并附有实例。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程