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 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程