簡體   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