Home > Backend Development > Golang > How to implement intersection of arrays in Golang

How to implement intersection of arrays in Golang

WBOY
Release: 2024-04-03 18:09:01
Original
1219 people have browsed it

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 数组求交集的实现方法

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
}
Copy after login

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
}
Copy after login

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}
Copy after login

Use the append function to find the intersection:

intersectionAB := intersection(a, b)
fmt.Println(intersectionAB) // [3 4 5 6]
Copy after login

Use map Find the intersection:

intersectionBA := intersection(b, a)
fmt.Println(intersectionBA) // [3 4 5 6]
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template