How to get intersection of two slice in golang?

前端 未结 5 1529
不思量自难忘°
不思量自难忘° 2021-02-18 22:24

Is there any efficient way to get intersection of two slices in Go?

I want to avoid nested for loop like solution
slice1 := []string{\"foo\", \"bar\",\"hello\"}         


        
5条回答
  •  北恋
    北恋 (楼主)
    2021-02-18 23:04

    How do I get the intersection between two arrays as a new array?

    • Simple Intersection: Compare each element in A to each in B (O(n^2))
    • Hash Intersection: Put them into a hash table (O(n))
    • Sorted Intersection: Sort A and do an optimized intersection (O(n*log(n)))

    All of which are implemented here

    https://github.com/juliangruber/go-intersect

提交回复
热议问题