I have two lists A and B (List). How to determine if they are equal in the cheapest way? I can write something like '(A minus B) union (B minus A) = empty set' or join them together and count amount of elements, but it is rather expensive. Is there workaround?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
If the ordering of the list items is relevant:
If the lists are to be treated as unordered sets:
(The
SequenceEqual
method and theHashSet<T>
constructor both have overloads that take anIEqualityComparer<T>
parameter, if you need that functionality.)A first shot - if they contain the same items, the union of both list should have the same number of items as any of both lists.
Note: Fails if one list is empty.
But it's probably still a
O(n²)
operation.Another solution - the lists must have the same length and list A minus list B must not contain any elements.
There isn't a shortcut here, really, unless the lists are sorted, in which case you can compare the elements one-by-one. And obviously I assume that order doesn't matter, or else it's obvious that you can compare them one-by-one then too.
Otherwise, I'd suggest that the most efficient algorithm you could get for large lists of items would probably be something like this, using a hash table to keep track of what you've seen (warning: haven't tested, but it should be clear what I'm getting at.)
Well, that depends on how you interpret your lists.
If you consider them as tuples (so the order of elements in lists matters), then you can go with this code:
If you consider your lists as sets (so the order of elements doesn't matter), then... you are using the wrong data structures I guess:
It depends on what you mean by "the list are equal". If you mean they contain the same objects, the solution suggested by Daniel is fine, just Union() the two list and count the items.
If by "equal" you mean that they have the same items in the same order, you'd be better off comparing the Count of both lists, then if they have the same count, just iterate with a plain
for loop
to compare each element from both lists at the same index. Less pretty but you can hardly be faster.