Home > Article > Backend Development > How to implement intersection of arrays in Golang
There are two common methods for finding the intersection of arrays in Golang: using the built-in append function, looping to determine whether the element is in another array, and superposing to find the intersection. Use map to exclude duplicate elements and obtain intersections efficiently by creating a mapping table.
Golang array intersection implementation method
In Golang, there are several methods to solve array intersection. This article will introduce the two most common methods: using the built-in append
function and using map
.
Method 1: Use the built-in append
function
append
function can add elements to an existing array, It is also possible to create a new array. We can use this feature to find the intersection:
func intersection(a, b []int) []int { result := []int{} for _, v := range a { if containsInArray(b, v) { result = append(result, v) } } return result } func containsInArray(arr []int, elem int) bool { for _, v := range arr { if v == elem { return true } } return false }
Method 2: Use map
Another way to find the intersection is to use map
. Compared with the append
function, using map
is more efficient because it can exclude duplicate elements in O(n) time complexity:
func intersection(a, b []int) []int { m := make(map[int]bool) for _, v := range a { m[v] = true } result := []int{} for _, v := range b { if m[v] { result = append(result, v) } } return result }
Practical case
Suppose we have the following two arrays:
a := []int{1, 2, 3, 4, 5, 6} b := []int{3, 4, 5, 6, 7, 8}
Use the append
function to find the intersection:
intersectionAB := intersection(a, b) fmt.Println(intersectionAB) // [3 4 5 6]
Use map
Find the intersection:
intersectionBA := intersection(b, a) fmt.Println(intersectionBA) // [3 4 5 6]
The above is the detailed content of How to implement intersection of arrays in Golang. For more information, please follow other related articles on the PHP Chinese website!