我有两套有序的 Integer
小号 - SortedSet<Integer>
,称他们为set1
和 set2
.我需要找到该集合的并集并返回子集偏移量 10 限制 10。我的意思是什么?
Set1:
1,2,5,6,7,8,11,21,23,543,1002
Set2:
11,12,15,16,17,8,111,121,123,1543,11002
Union:
1,2,5,6,7,8,11,21,23,543,1002,12,15,16,17,111,121,123,1543,11002
Union offset 10 limit 10:
1002,12,15,16,17,111,121,123,1543,11002
请注意,8
的基数和 11
在联盟中是1
.
我正在寻找一种算法,它允许我不将整个集合加载到内存中(因为这些集合可能非常大,我不会浪费服务器的资源)。有没有办法做到这一点?也许一些即时库,如 commons
或 guava
有什么帮助吗?
UPD:我自己不使用 Java 8,但使用它的解决方案也很有趣。
最佳答案
算法很简单。
Create empty hash Create empty array Set waste counter to 0 Iterate all sets (2 or more) Iterate set values If value not in hash Insert value into hash Increase waste counter If waste counter > offset (10) Insert value into array If array length == limit (10) Done - return array
关于java - 集合的偏移量和限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30636786/