Is this approach to check duplicates in an array relatively efficient? Why or why not?

醉酒当歌 提交于 2020-01-15 08:20:08

问题


I just wanted to check whether there contains any duplicates in my array. I searched on Google and see some approaches:

  • Double for-loop loops though the array and comparing each item
  • Creating a dictionary that stores the number of occurrences of each item

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.

If I only have at most 50 items in the array, will this even matter?


回答1:


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 Sets from scratch.




回答2:


My first thought was to create a set and to see if the number of elements was different than the array, just like you. Apple will probably have optimized this conversion fairly well and doing it this way makes the code compact and easy to understand.

You don't mention what the array is for and how it's used but could you just use a set instead of the array so that duplicates don't get added in the first place? Or if you need to keep track of how many but still need to know the unique values easily then create a new class that uses a dictionary for the storage. The key is what you are storing in the array but would be unique and the value would be the count.



来源:https://stackoverflow.com/questions/37140158/is-this-approach-to-check-duplicates-in-an-array-relatively-efficient-why-or-wh

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!