Go語言程式:計算兩個切片的交集


在 Go 語言中,切片 (slice) 就像陣列一樣,是一系列元素的序列。陣列是固定長度的元素序列,而切片是動態陣列,這意味著它的值不是固定的,可以更改。切片比陣列更高效、更快,並且是按引用傳遞而不是按值傳遞。

語法

func append(slice, element_1, element_2…, element_N) []T

append 函式用於向陣列切片新增值。它接受多個引數。第一個引數是要新增值的陣列,後跟要新增的值。然後,該函式返回包含所有值的最終陣列切片。

func make ([] type, size, capacity)

Go 語言中的 make 函式用於建立陣列/對映,它接受要建立的變數型別、大小和容量作為引數。

func append(slice, element_1, element_2…, element_N) []T

append 函式用於向陣列切片新增值。它接受多個引數。第一個引數是要新增值的陣列,後跟要新增的值。然後,該函式返回包含所有值的最終陣列切片。

演算法

  • 步驟 1 - 建立一個 main 包,並在程式中宣告 fmt(格式化包),其中 main 生成可執行程式碼,fmt 幫助格式化輸入和輸出。

  • 步驟 2 - 建立一個 main 函式,並在該函式中建立一個 slice1 和 slice2,使用 Go 語言中的 print 語句在控制檯上列印該切片。

  • 步驟 3 - 使用兩個切片引數呼叫 intersect 函式,對這兩個切片的元素進行交集運算。

  • 步驟 4 - 在 intersect 函式中建立一個空的切片 intersect,用於追加元素。

  • 步驟 5 - 執行一個 for 迴圈來計算兩個切片的交集。

  • 步驟 6 - 迴圈終止後,將切片返回到 intersect 函式,並使用 fmt.Println() 函式(其中 ln 表示換行)在控制檯上列印它。

示例 1

在這個示例中,我們將使用巢狀 for 迴圈來計算兩個切片的交集。在這個示例中,我們將檢查兩個元素是否相等,如果相等,則將其追加到建立的切片中。讓我們一起了解演算法和程式碼,以便對這個概念有一個清晰的理解。

package main
import (
   "fmt"
)
func main() {
   myslice1 := []int{10, 20, 30, 40, 50} //create slice1
   fmt.Println("The elements of slice1 are:", myslice1)
   myslice2 := []int{30, 40, 50, 60, 70} //create slice2
   fmt.Println("The elements of slice2 are:", myslice2)
   intersect := intersect(myslice1, myslice2)
   fmt.Println(intersect)
}
func intersect(slice1, slice2 []int) []int {
   var intersect []int
   for _, element1 := range slice1 {
      for _, element2 := range slice2 {
         if element1 == element2 {
            intersect = append(intersect, element1)
         }
      }
   }
   return intersect //return slice after intersection
}

輸出

The elements of slice1 are: [10 20 30 40 50]
The elements of slice2 are: [30 40 50 60 70]
[30 40 50]

示例 2

在這個示例中,我們將學習如何使用 map 函式計算兩個切片的交集。我們將把那些值大於 0 的元素追加到新的切片中。讓我們一起了解演算法和程式碼,以便對這個概念有一個清晰的理解。

package main
import (
   "fmt"
)
func main() {
   myslice1 := []int{10, 20, 30, 40, 50} //create slice1
   fmt.Println("The elements of slice1 are:", myslice1)
   myslice2 := []int{30, 40, 50, 60, 70} //create slice2
   fmt.Println("The elements of slice2 are:", myslice2)
   intersect := intersect(myslice1, myslice2)
   fmt.Println("The elements of slice after intersection are:")
   fmt.Println(intersect)
}
func intersect(myslice1, myslice2 []int) []int {
   k := make(map[int]int) //create map to store elements
   for _, num := range myslice1 {
      k[num]++
   }
   var output []int
   for _, num := range myslice2 {
      if k[num] > 0 {
         output = append(output, num)
         k[num]--
      }
   }
   return output //return slice after intersection
}

輸出

The elements of slice1 are: [10 20 30 40 50]
The elements of slice2 are: [30 40 50 60 70]
The elements of slice after intersection are:
[30 40 50]

結論

在上面的程式中,我們使用了兩個示例來計算兩個切片的交集。在第一個示例中,我們使用了巢狀 for 迴圈,在第二個示例中,我們使用了 map 函式。

更新於:2023年2月13日

1K+ 次瀏覽

啟動您的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.