简体   繁体   English

如何避免时间复杂度O(n^2)?

[英]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: 笔记:

  • note the use of an identity hashset; 注意使用标识哈希集; you may want to implement equals/hashcode for the references instead (or maybe the type you use has them already implemented for you); 您可能希望为引用实现equals / hashcode(或者您使用的类型已经为您实现了它们);
  • your map may be filled as articles "flow by", in this case you can create it only once (make it thread safe if so!). 您的地图可能会被填充为“流经”的文章,在这种情况下,您只能创建一次(如果是这样,请使其线程安全!)。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM