方法来判断如果两个数组是相同的? [英] Way to judge if two Arrays are identical?

查看:150
本文介绍了方法来判断如果两个数组是相同的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

相同我的意思是一个数组包含相同的元素,以便数组中的元素都不是事在这里。

By identical I mean two Arrays contain same elements, order of elements in Arrays are not matter here.

我想出了解决的办法是这样的(果然出了错误的方法,因为在注释中指出的的):

The solution I came up with is like this(which turns out a wrong approach as pointed out in comments):


 if the size of two Arrays are equal
 See True, find all elements of Array A in Array B
 All Found,  find all elements of Array B in Array A
 All Found, then I get conclusion two Arrays are identical

不过,有没有时间复杂度来看更好的算法?

However, is there better algorithm in term of time complexity?

推荐答案

假设你有一个用户[] 阵列1和用户[] 阵列2.您可以通过阵列中的一个垂耳,并将它们添加到词典<使用者,INT> 词典,其中关键是用户和值计数。然后,你通过第二阵列和用于在阵列2减量每个用户在词典的计数循环(如果计数大于1)或取出元件(如果计数为1)。如果用户不是在字典中,那么你就可以停止,该阵列不匹配。

Let's say you have an User[] array 1 and User[] array 2. You can lop through array one and add them to Dictionary<User, int> dictionary where the key is the user and the value is a count. Then you loop through the second array and for each user in array 2 decrement the count in the dictionary (if count is greater than 1) or remove the element (if count is 1). If the user isn't in the dictionary, then you can stop, the arrays don't match.

如果你到了年底了previously检查数组的长度是一样的,那么阵列匹配。如果你没有检查长度早期(当然你仍然应该有),那么你可以验证词典现在通过后阵列2完全循环空。

If you get to the end and had previously checked length of the arrays is same, then the arrays match. If you hadn't checked length earlier (which of course you still should have), then you can just verify the dictionary is now empty after completely looping through array 2.

我不知道究竟这个性能,但它会比排序两份名单,并通过他们循环利用元素的元素比较快。需要更多的内存,虽然,但如果数组不是超级大那么内存的使用不应该是一个问题。

I don't know exactly what the performance of this is, but it will be faster than sorting both lists and looping through them comparing element by element. Takes more memory though, but if the arrays are not super large then memory usage shouldn't be an issue.

这篇关于方法来判断如果两个数组是相同的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆