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