[英]What is the time complexity of using retainAll() function between List and HashMap?
Let's say i have a nested List which contains n^2 element in it and also i have a HashMap which contains n^2 keys in it.假设我有一个嵌套列表,其中包含 n^2 元素,并且我有一个 HashMap ,其中包含 n^2 个键。 I want to get common elements between the list and hashmap with using
retainAll()
function.我想通过使用
retainAll()
function 获得列表和 hashmap 之间的共同元素。 What is the time complexity of retainAll() in this case?在这种情况下,retainAll() 的时间复杂度是多少?
List<List<Integer> list = new ArrayList<>();
Map<List<Integer>, Integer> hashmap = new HashMap<List<Integer>, Integer>();
list.retainAll(hashmap);
To get the commons,i'm using this loop but it has n^2 complexity.为了获得共同点,我正在使用这个循环,但它有 n^2 的复杂性。
List<List<Integer>> commons = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
if (hashmap.get(list.get(i)) != null) {
commons.add(list.get(i));
}
}
Also if you have an algorithm which has better time complexity to get intersection of them, i need it.此外,如果您有一个具有更好时间复杂度的算法来获得它们的交集,我需要它。
EDIT: Actually the problem is, i have a list of integers size of n.编辑:实际上问题是,我有一个大小为 n 的整数列表。 But i divided that list into sublists and sublists count became n^2.
但我将该列表划分为子列表,子列表计数变为 n^2。 Since i want to find out that hashmap contains every sublist as a key in it, i used n^2 in question.
因为我想知道 hashmap 包含每个子列表作为其中的键,所以我使用了 n^2 。 But it's too big according to my whole project.
但根据我的整个项目,它太大了。 I'm searching complexity decreasing ways.
我正在寻找降低复杂性的方法。
Well, I mean if you have n^2
items in the list then the complexity is O(n^2)
, although this a really weird thing to say.好吧,我的意思是,如果列表中有
n^2
项,那么复杂度就是O(n^2)
,尽管说起来真的很奇怪。 Usually n
is the size of the collection, so the time complexity of retainAll
is consider O(n)
.通常
n
是集合的大小,因此retainAll
的时间复杂度是O(n)
。
It's impossible to have an algorithm that produces a better time complexity for this, as far as I can think of.据我所知,不可能有一种算法为此产生更好的时间复杂度。 You have to iterate the list at least once...
您必须至少迭代一次列表...
What you can do is switch your data structure.你可以做的是切换你的数据结构。 Read more: Data structures for fast intersection operations?
阅读更多: 用于快速交叉路口操作的数据结构?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.