5

[Golang] Intersection of Two Arrays

 2 years ago
source link: http://siongui.github.io/2018/03/09/go-match-common-element-in-two-array/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

[Golang] Intersection of Two Arrays

March 09, 2018

Find common elements in two arrays, i.e., intersection or matches in two arrays. There are many ways to find the intersection [1] [3]. Here we will implement the method mentioned in [2].

The idea is to convert one array to the data structure of key-value pairs, i.e., hash table. The hash table in Go is built-in map type. Then we check if items of the other array is in the hash table. If yes, the item is in the intersection of the two arrays.

The following is example of above idea.

Run Code on Go Playground

package main

import (
      "fmt"
)

func Intersection(a, b []int) (c []int) {
      m := make(map[int]bool)

      for _, item := range a {
              m[item] = true
      }

      for _, item := range b {
              if _, ok := m[item]; ok {
                      c = append(c, item)
              }
      }
      return
}

func main() {
      var a = []int{1, 2, 3, 4, 5}
      var b = []int{2, 3, 5, 7, 11}
      fmt.Println(Intersection(a, b))
}

The result will be [2 3 5].

For union of two arrays, see [5].

Tested on: Go Playground


References:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK