[Golang] Union of Two Arrays
source link: https://siongui.github.io/2018/03/10/go-set-of-all-elements-in-two-arrays/
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.
[Golang] Union of Two Arrays
March 10, 2018Find the set of all elements in two arrays, i.e., union of two arrays. This is the continued work of my post yesterday [1], which is intersection of two arrays.
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 not, append the item to the first array, and return the first array after finish.
The following is example of above idea.
package main import ( "fmt" ) func Union(a, b []int) []int { m := make(map[int]bool) for _, item := range a { m[item] = true } for _, item := range b { if _, ok := m[item]; !ok { a = append(a, item) } } return a } func main() { var a = []int{1, 2, 3, 4, 5} var b = []int{2, 3, 5, 7, 11} fmt.Println(Union(a, b)) }
The result will be [1 2 3 4 5 7 11].
Tested on: Go Playground
References:
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK