doushuo1989 2018-09-18 22:35
浏览 64
已采纳

检查两个数组是否具有相同成员的最佳方法

I have an array of strings, I need to compare this to another array of strings, but they may be in a different order. What's the best way to compare the two arrays?

This is what I have so far, just wondering if there is a simpler / more efficient way I'm missing.

func unorderedEqual(first, second []string) bool {
    if len(first) != len(second) {
        return false
    }
    for _, value := range first {
        if !contains(value, second) {
            return false
        }
    }
    return true
}

func contains(needle string, haystack []string) bool {
    for _, matchValue := range haystack {
        if matchValue == needle {
            return true
        }
    }
    return false
}
  • 写回答

4条回答 默认 最新

  • 普通网友 2018-09-18 22:46
    关注

    Given that you are doing a length check, I'm going to go with the assumption that implies that they are 1:1, just ordered differently.

    You can do this in one pass (each) using a map[string]bool to check existence in both. This utilizes the fact that the map returns the zero value of a bool, which is false, when the key is not present.

    Disclaimer: Technically this is order O(n)*O(map). The Go Programming Language Specification does not make any performance guarantees for map types.

    https://play.golang.org/p/2LUjN5LkXLL

    func unorderedEqual(first, second []string) bool {
        if len(first) != len(second) {
            return false
        }
        exists := make(map[string]bool)
        for _, value := range first {
            exists[value] = true
        }
        for _, value := range second {
            if !exists[value] {
                return false
            }
        }
        return true
    }
    

    If you want to get nit-picky about memory usage, you could save yourself storing a bunch of bools (which is usually negligible, but to each their own) by using a map[string]struct{} (the empty struct), and you just check existence a little differently, as in this example.

    https://play.golang.org/p/MjwP_wCtYZV

    Set

    exists[value] = struct{}{}
    

    Check

    if _, ok := exists[value]; !ok {
        return false
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏