doujiang1993 2018-06-28 08:33
浏览 72
已采纳

从两个切片的重复项创建切片

I have two slices:

slice1 := []string{"a", "b", "c", "d"}
slice2 := []string{"c", "d", "e", "f"}

Expected result:

[]string{"c", "d"}

What's the best way to create a slice from duplicate items of slice1 and slice2 with this specifications:

  1. Minimum code
  2. Slices are large
  3. Slices are not sorted
  4. Do not modify the slices
  5. They may not contain the duplicates

This is what I have tried:

slice1 := []string{"a", "b", "c", "d"}
slice2 := []string{"c", "d", "e", "f"}
duplicateItems := []string{}
for _, item1 := range slice1 {
    for _, item2 := range slice2 {
        if item1 == item2 {
            duplicateItems = append(duplicateItems, item1)
        }
    }
}

fmt.Println(duplicateItems) // [c d]
  • 写回答

1条回答 默认 最新

  • donglengli0644 2018-06-28 09:26
    关注

    This method sacrifices memory usage for big O complexity (speed).

    // flatten the first slice into a map for O(1) constant time lookup
    m1 := make(map[string]struct{})
    for _, v := range slice1 {
        m1[v] = struct{}{}
    }
    
    var dup []string
    
    // iterate slice 2, using the O(1) lookup.
    for _, v := range slice2 {
        if _, exists := m1[v]; exists {
            dup = append(dup, v)
        }
    }
    
    // dup contains the duplicates
    

    You only visit each of the elements once, but the memory requirements are much larger as slice1 needs to be stored in the map.

    You could extend this code to flatten the smallest of the 2 slices into the map, for less memory requirements.

    it's worth noting that map[string]struct{} is used instead of map[string]bool because struct{} uses zero bytes of memory

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请问如何在openpcdet上对KITTI数据集的测试集进行结果评估?
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错