[英]How to avoid time complexity O(n^2)?
I have this following piece of code:我有以下这段代码:
for(ArticleBasketInBean basketBean : bean.getBasket()) {
for(ArticleDTO article : dto.getArticleList()) {
if(basketBean.getArticleReference().equals(article.getArticleReference())) {
article.setAddedToBasket(true);
}
}
}
Clearly the time complexity of the above operation is O(n^2).显然上述操作的时间复杂度是O(n^2)。 For this case
articleReference
is unique.对于这种情况,
articleReference
是唯一的。 So the list returned by bean.getBasket()
has no duplicate articleReference
, also this is true for the list returned by dto.getArticleList()
.所以
bean.getBasket()
返回的列表没有重复的articleReference
,对于dto.getArticleList()
返回的列表也是如此。
I want to avoid this nested iteration and want to write faster code.我想避免这种嵌套迭代并希望编写更快的代码。 How can I do that?
我怎样才能做到这一点?
Use java.util.HashSet
to cache one of the sets of references, assuming the sets are not TOO large, of course. 当然,使用
java.util.HashSet
来缓存其中一组引用,假设这些集合不是TOO大。 With a good hash function, this should bring you back to O(n). 有了很好的哈希函数,这会让你回到O(n)。
A simple break
will save you. 一个简单的
break
将拯救你。
for(ArticleBasketInBean basketBean : bean.getBasket()) {
for(ArticleDTO article : dto.getArticleList()) {
if(basketBean.getArticleReference().
equals(article.getArticleReference())) {
article.setAddedToBasket(true);
break;
}
}
}
If you don't have too many articles/baskets and as you say the references are unique you can do something like this; 如果你没有太多的文章/篮子,并且正如你所说,参考文献是独一无二的,你可以做这样的事情; let's call
R
the type of the reference, A
the type of articles, B
the type of baskets: 让我们称
R
为参考类型, A
为文章类型, B
为篮子类型:
// since all references are unique we can use that, but see below
Map<R, A> mappedArticles = new IdentityHashMap<>();
// inject articles based on references in the map, then
A article;
for (B basket: bean.getBasket())
article = mappedArticles.get(basket.getArticleReferences());
if (article != null)
article.setAddedToBasket(true);
// Full list of articles is in the map's .values()
Notes: 笔记:
This is where hashMap Data Structure comes to rescue.这就是hashMap数据结构的用武之地。 It's not any rocket science, simply:
这不是什么火箭科学,只是:
an object with key, value pair
带有键值对的 object
The complexity will reduce from O(n2) to O(n), which is better.复杂度会从O(n2)降低到O(n),这样更好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.