什么是比较两个数组是否相等的最快方法? [英] What's the fastest way to compare two arrays for equality?
问题描述
我有可能具有相同的值的对象的两个数组,但在不同的顺序,例如
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?
推荐答案
我不能保证,这是的最快的,但它肯定是非常有效的:
I can't guarantee that this is the fastest, but it's certainly quite efficient:
bool areEquivalent = array1.Length == array2.Length
&& new HashSet<string>(array1).SetEquals(array2);
编辑: SaeedAlg和Sandris提高对重复造成的问题,这种方法的不同频率的有效分。我可以看到两种解决方法,如果这是很重要的(没有给予过多考虑到它们各自的效率):
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阵列,然后依次进行比较。这种方法,在理论上,应该有二次在最坏的情况下的复杂性。 例如:
1.Sort the arrays and then compare them sequentially. This approach, in theory, should have quadratic complexity in the worst case. E.g.:
return array1.Length == array2.Length
&& array1.OrderBy(s => s).SequenceEqual(array2.OrderBy(s => s));
2.Build了每个数组中字符串的频率表,然后对它们进行比较。例如:
2.Build up a frequency-table of strings in each array and then compare them. E.g.:
if(array1.Length != array2.Length)
return false;
var f1 = array1.GroupBy(s => s)
.Select(group => new {group.Key, Count = group.Count() });
var f2 = array2.GroupBy(s => s)
.Select(group => new {group.Key, Count = group.Count() });
return !f1.Except(f2).Any();
这篇关于什么是比较两个数组是否相等的最快方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!