POPMUISE
理想情况下,这将是一个评论,但 TLDR 是使用 Husain 的排序和比较更正确和更快。细节。对于查看上面 RayfenWindspear 答案(当前排名最高)的任何人,乍一看它看起来是正确的,但请注意它不检查完全相等性,而只是检查第二个列表中的每个元素都在第一个列表中. 反之亦然,但不通过此方法检查。因此它没有通过这个测试(bb重复):assert.False(t, unorderedEqual([]string{"aa", "cc", "bb"}, []string{"aa", "bb", "bb"}))当然你可以只运行两次就得到正确的结果,这只是一个线性因素func DoubleUnorderedEqual(a, b []string) bool { return unorderedEqual(a, b) && unorderedEqual(b, a)}Husain 提出的先排序后检查的建议可能排名更高,因为它是正确的,而且对于较大的列表也更快。这是 Husain 在导出函数中的代码:func SortCompare(a, b []string) bool { if len(a) != len(b) { return false } sort.Strings(a) sort.Strings(b) for i, v := range a { if v != b[i] { return false } } return true}还有一些你可以在上面运行的测试(它通过了)func TestSortCompare(t *testing.T) { assert.True(t, SortCompare([]string{"aa"}, []string{"aa"})) assert.False(t, SortCompare([]string{"aa"}, []string{"bb"})) assert.False(t, SortCompare([]string{"aa"}, []string{"bb", "cc"})) assert.True(t, SortCompare([]string{"cc", "bb"}, []string{"bb", "cc"})) assert.True(t, SortCompare([]string{"aa", "cc", "bb"}, []string{"aa", "bb", "cc"})) assert.False(t, SortCompare([]string{"aa", "cc", "bb"}, []string{"aa", "bb", "bb"}))}这是一些示例基准测试....func getStrings() ([]string, []string) { a := []string{"a", "foo", "bar", "ping", "pong"} b := []string{"pong", "foo", "a", "bar", "ping"} return a, b}func BenchmarkSortCompare(b *testing.B) { s0, s1 := getStrings() var outcome bool for n := 0; n < b.N; n++ { outcome = SortCompare(s0, s1) } fmt.Println(outcome)}func BenchmarkDoubleUnorderedEqual(b *testing.B) { s0, s1 := getStrings() var outcome bool for n := 0; n < b.N; n++ { outcome = DoubleUnorderedEqual(s0, s1) } fmt.Println(outcome)}结果...BenchmarkSortCompare-32 2637952 498 ns/opBenchmarkDoubleUnorderedEqual-32 3060261 381 ns/op所以在这个小尺寸下运行两次 map 方法稍微快一些......但是添加更多的字符串并且 sort 方法胜出 10 倍。我没有考虑字符串中混乱程度的影响但是它们足够混乱,乍一看这并不是一个明显不公平的测试。func getStrings2() ([]string, []string) { a := []string{"a", "foo", "bar", "ping", "pong", "b", "c", "g", "e", "f", "d", "h", "i", "j", "q", "l", "n", "o", "p", "k", "r", "s", "t", "u", "v", "w", "x", "y", "z"} b := []string{"pong", "foo", "a", "bar", "ping", "p", "r", "q", "s", "u", "t", "v", "j", "x", "y", "z", "b", "e", "d", "c", "h", "g", "f", "i", "w", "k", "l", "n", "o"} return a, b}func BenchmarkSortCompare2(b *testing.B) { s0, s1 := getStrings2() var outcome bool for n := 0; n < b.N; n++ { outcome = SortCompare(s0, s1) } fmt.Println(outcome)}func BenchmarkDoubleUnorderedEqual2(b *testing.B) { s0, s1 := getStrings2() var outcome bool for n := 0; n < b.N; n++ { outcome = DoubleUnorderedEqual(s0, s1) } fmt.Println(outcome)}结果:BenchmarkSortCompare2-32 454641 2797 ns/opBenchmarkDoubleUnorderedEqual2-32 44420 26714 ns/op结论 - 我将使用 Husain 的排序和比较......