这种方法可以检查数组中的重复项比较有效吗?为什么或者为什么不? [英] Is this approach to check duplicates in an array relatively efficient? Why or why not?
问题描述
我只想检查我的数组中是否包含任何重复项。我在Google上搜索并看到一些方法:
I just wanted to check whether there contains any duplicates in my array. I searched on Google and see some approaches:
- 通过数组进行双重循环循环,并比较每个项目
- 创建一个存储每个项目出现次数的字典
但是这些方法需要很多循环,这种懒惰为这个功能写了大量的代码。 xD。
But these methods require a lot of loops and I'm kind of lazy to write a large amount of code just for this functionality. xD.
所以我想到了这种创意的方式:
So I thought of this creative way:
let containsDuplicates = Set(array).count != array.count
但是,这种方法是更快还是慢比其他两个?我不确定,因为它似乎创建一个我认为需要循环通过数组的集合。我不知道访问计数
是否也循环遍历整个数组。
However, is this method faster or slower than the other two? I'm not sure because it seems to create a set which I think needs to loop through the array. And I don't know whether accessing the count
also loops through the whole array.
如果我只有数组中最多的50个项目,这个甚至是重要的吗?
If I only have at most 50 items in the array, will this even matter?
推荐答案
这几乎是最好的方法。字典存储是恒定时间,每个项目只需要存储一次,因此它是一个 O(n)
解决方案,而$ code> O(n ^ 2)用于双循环方法。空间效率较低,但这几天通常不是一个问题。
That's pretty much the best way. Dictionary storage is constant time, and each item only needs to be stored once, so it's an O(n)
solution, vs the O(n^2)
for the double for-loop approach. The space efficiency is lower, but that's usually not a concern these days.
如果你经常这样做,我会建议使用某种混合数据结构,所以你不是不断地生成这些从头开始设置
。
If you're doing this often, I would suggest using some kind of hybrid data structure, so that you're not constantly generating these Set
s from scratch.
这篇关于这种方法可以检查数组中的重复项比较有效吗?为什么或者为什么不?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!