繁体   English   中英

Big O:这个算法的时间复杂度是多少?

[英]Big O: what is the time complexity for this algorithm?

下面我的方法的最佳情况和最坏情况时间复杂度是多少?

我知道 ArrayList.add() 的时间复杂度为 O(1) 但不确定loaded.stream().distinct().collect(Collectors.toList());

  public static int countUnique(WordStream words) {

    ArrayList<String> loaded = new ArrayList<String>();
    ArrayList<String> empty = new ArrayList<String>();

    // Fill loaded with WordStream words
    for (String i : words) {
      loaded.add(i);
    }

    empty = (ArrayList<String>) loaded.stream().distinct().collect(Collectors.toList());

    return empty.size();
  }

首先, ArrayList()不是所有操作的 O(1) ,而是add()

distinct()是 O(n),因为它必须检查所有元素。 每次迭代都是 O(1),因为它由一个 O(1) 的 HashSet 支持。

您可以将代码替换为:

return (int)loaded.parallelStream().distinct().count();

这会快很多,但仍然是 O(n)

您可以通过不使用流来更简洁地实现这一点:

HashSet<String> loaded = new HashSet<>();
for (String i : words) {
  loaded.add(i);
}
return loaded.size();

由于您已串行执行此循环,因此您不会从并行流中获得太多好处。

这种方法也是 O(n)。


正如@Holger 所指出的,如果WordStream是一个Collection (而不仅仅是一个可迭代的),它可以更简洁地实现:

return new HashSet<>(words).size();

但是,在WordStream是否实际上是Collection的问题中没有指定。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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