【发布时间】:2021-04-20 00:16:19
【问题描述】:
假设我有一个嵌套列表,其中包含 n^2 个元素,并且我有一个 HashMap,其中包含 n^2 个键。我想使用retainAll() 函数获取列表和哈希图之间的共同元素。这种情况下retainAll()的时间复杂度是多少?
List<List<Integer> list = new ArrayList<>();
Map<List<Integer>, Integer> hashmap = new HashMap<List<Integer>, Integer>();
list.retainAll(hashmap);
为了获得共同点,我正在使用这个循环,但它有 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));
}
}
另外,如果你有一个算法具有更好的时间复杂度来获得它们的交集,我需要它。
编辑: 实际上问题是,我有一个大小为 n 的整数列表。但我将该列表划分为子列表,子列表计数变为 n^2。因为我想找出 hashmap 包含每个子列表作为其中的键,所以我使用了 n^2 。但根据我的整个项目,它太大了。我正在寻找降低复杂性的方法。
【问题讨论】:
-
好像是this的副本
-
@GuilhermeSchaidhauerCastro 我在这篇文章之前检查了它,但我不能确定它是否相同。 HashSet 和 HashMap 可能会造成差异。我也无法清楚地得到答案。
标签: java algorithm arraylist hashmap big-o