How to get intersection of two slice in golang?

前端 未结 5 1513
不思量自难忘°
不思量自难忘° 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条回答
  •  闹比i
    闹比i (楼主)
    2021-02-18 22:58

    It's a best method for intersection two slice. Time complexity is too low.

    Time Complexity : O(m+n)

    m = length of first slice.

    n = length of second slice.

    func intersection(s1, s2 []string) (inter []string) {
        hash := make(map[string]bool)
        for _, e := range s1 {
            hash[e] = true
        }
        for _, e := range s2 {
            // If elements present in the hashmap then append intersection list.
            if hash[e] {
                inter = append(inter, e)
            }
        }
        //Remove dups from slice.
        inter = removeDups(inter)
        return
    }
    
    //Remove dups from slice.
    func removeDups(elements []string)(nodups []string) {
        encountered := make(map[string]bool)
        for _, element := range elements {
            if !encountered[element] {
                nodups = append(nodups, element)
                encountered[element] = true
            }
        }
        return
    }
    

提交回复
热议问题