比较两个数组是否相等的最快方法是什么?
我有两个对象数组,它们可能具有相同的值,但顺序不同,例如
{ "cat", "dog", "mouse", "pangolin" }
{ "dog", "pangolin", "cat", "mouse" }
我希望将这两个数组视为相等。测试这个的最快方法是什么?
I have two arrays of objects which are likely to have the same values, but in a different order, e.g.
{ "cat", "dog", "mouse", "pangolin" }
{ "dog", "pangolin", "cat", "mouse" }
I wish to treat these two arrays as equal. What's the fastest way to test this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我不能保证这是最快的,但它肯定非常有效:
编辑:
SaeedAlg 和 Sandris 提出了关于不同重复频率导致此方法出现问题的有效观点。如果这很重要,我可以看到两种解决方法(没有过多考虑它们各自的效率):
1.对数组进行排序,然后按顺序比较它们。理论上,这种方法在最坏的情况下应该具有二次复杂度。
例如:
2.建立每个数组中字符串的频率表,然后比较它们。例如:
I can't guarantee that this is the fastest, but it's certainly quite efficient:
EDIT:
SaeedAlg and Sandris raise valid points about different frequencies of duplicates causing problems with this approach. I can see two workarounds if this is important (haven't given much thought to their respective efficiencies):
1.Sort the arrays and then compare them sequentially. This approach, in theory, should have quadratic complexity in the worst case.
E.g.:
2.Build up a frequency-table of strings in each array and then compare them. E.g.:
我认为唯一合理的方法就是对它们进行排序然后进行比较。
排序需要
O(n logn)
并进行比较O(n)
,因此总共仍然是O(n logn)
I think the only reasonable way is to sort them and then compare.
Sorting requires
O(n logn)
and comparingO(n)
, so that's still a total ofO(n logn)
将两个数组都转换为 HashSet 并使用 setequals
Convert both arrays to HashSets and use setequals
你有没有尝试过类似的东西
Have you tried something like
我会使用 HashSet,假设没有重复项
编辑:
如果只有四个元素,跳过 HashSet 并在比较中使用 arr1.Contains 可能会更快。测量并选择最适合您的阵列大小的最快的。
I would use a HashSet, assuming there are no duplicates
Edit:
If you just have four elements it might be faster to skip the HashSet and use arr1.Contains in the comparison. Measure and pick the fastest for your array size.
伪代码 :
Pseudocode :