首页 > 文章列表 > Golang 数组求交集的实现方法

Golang 数组求交集的实现方法

数组 golang
156 2024-04-23

Golang 数组求交集有两种常用方法:使用内置 append 函数,通过循环判断元素是否在另一个数组中,叠加求交集。使用 map,通过创建映射表排除重复元素并高效获取交集。

Golang 数组求交集的实现方法

Golang 数组求交集的实现方法

在 Golang 中,求解数组交集有几种方法。本文将介绍两种最常用的方法:使用内置的 append 函数和使用 map

方法 1:使用内置的 append 函数

append 函数可以将元素添加到现有数组中,也可以创建一个新数组。我们可以利用这个特性来求交集:

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
}

方法 2:使用 map

另一种求交集的方法是使用 map。与 append 函数相比,使用 map 的效率更高,因为它可以 O(n) 的时间复杂度排除重复元素:

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
}

实战案例

假设我们有以下两个数组:

a := []int{1, 2, 3, 4, 5, 6}
b := []int{3, 4, 5, 6, 7, 8}

使用 append 函数求交集:

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

使用 map 求交集:

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