C#创建随机唯一整数列表 [英] C# creating a list of random unique integers
问题描述
我需要创建一个包含十亿个整数的列表,并且它们都必须是唯一的.我还需要非常快地完成此操作.
I need to create a list with one billion integers and they must all be unique. I also need this to be done extremely fast.
创建列表并一个接一个地添加随机数,然后检查每个副本是否重复非常慢.
Creating a list and adding random numbers one by one and checking to see if each one is a duplicate is extremely slow.
如果我只是用随机数填充列表而不检查它们是否重复,然后使用distinct().toList(),这似乎会很快.我重复此操作,直到没有更多重复为止.但是,创建新列表使用的额外内存不是最佳的.有没有一种方法可以提高distinct()的性能,但是只创建源列表,而不是创建新列表,就可以了?
It seems to be quite fast if I just populate a list with random numbers without checking if they are duplicates and then using distinct().toList(). I repeat this until there are no more duplicates. However the extra memory used by creating a new list is not optimal. Is there a way to get the performance of distinct() but instead of creating a new list it just modifies the source list?
推荐答案
整数是否需要在一定范围内?如果是这样,则可以创建一个数组或列表,其中所有数字都在该范围内(例如,从1到1000000000),然后对列表进行随机排列.
Do the integers need to be in a certain range? If so, you could create an array or list with all numbers in that range (for example from 1 to 1000000000) and shuffle that list.
这篇关于C#创建随机唯一整数列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!