簡體   English   中英

為什么此方法的時間復雜度為2 * O(n log n)+ O(m log m)?

[英]Why is this method's time complexity 2*O(n log n) + O(m log m)?

下面的代碼嘗試檢查searchWords所有單詞是否都出現在newsPaperWords 兩個列表都可以包含重復項。 如果出現一個字N在次searchWords ,它必須出現至少n次newsPaperWords該方法返回true。 我以為時間復雜度是2*O(n) + O(m)但面試官告訴我這是2*O(n log n) + O(m log m)

/**
 * @param searchWords The words we're looking for. Can contain duplicates
 * @param newsPaperWords  The list to look into
 */
public boolean wordMatch(List<String> searchWords, List<String> newsPaperWords) {
    Map<String, Integer> searchWordCount = getWordCountMap(searchWords);
    Map<String, Integer> newspaperWordCount = getWordCountMap(newsPaperWords);
    for (Map.Entry<String, Integer> searchEntry : searchWordCount.entrySet()) {
        Integer occurrencesInNewspaper = newspaperWordCount.get(searchEntry.getKey());
        if (occurrencesInNewspaper == null || occurrencesInNewspaper < searchEntry.getValue()) {
            return false;
        }
    }
    return true;
}

private Map<String, Integer> getWordCountMap(List<String> words) {
    Map<String, Integer> result = new HashMap<>();
    for (String word : words) {
        Integer occurrencesThisWord = result.get(word);
        if (occurrencesThisWord == null) {
            result.put(word, 1);
        } else {
            result.put(word, occurrencesThisWord + 1);
        }
    }
    return result;
}

我看到它,該方法的時間復雜度是2*O(n) + O(m)即n個元素的數量searchWords和M元素的數量newsPaperWords ):

  • 方法getWordCountMap()的復雜度為O(n) ,即給定列表中元素的數量為n。 該方法循環一次列表,並假設對result.get(word)result.put()的調用是O(1)
  • 然后,最壞的情況是searchWordCount.entrySet()的迭代是O(n) ,再次假設對Hashmap.get()調用是O(1)

因此,只需添加O(n) + O(m)即可構建兩個地圖,並為最后的外觀添加O(n)

看完這個答案 ,以O(n)最壞情況的復雜性HashMap.get()我能理解的復雜性getWordCountMap()上升到O(n*2n)和最終環路O(n*n) ,這將使總復雜度為O(n*2n) + O(m*2m) + O(n*n)

但是2*O(n log n) + O(m log m)呢?

由於JEP 180:用平衡樹處理頻繁的HashMap沖突 HashMap.get()操作的最壞情況是O(log n) 引用JEP 180:

基本思想是,一旦哈希存儲桶中的項目數超過某個閾值,該存儲桶就會從使用條目的鏈接列表切換到平衡樹。 在高哈希沖突的情況下,這將改善從O(n)到O(log n)的最壞情況下的性能。

這將使getWordCountMap()方法成為O(n log n)

假設哈希圖使用適當的哈希函數,則您推論出的復雜度是正確的。 對我來說,這種算法看起來像O(m + n)


我想您的面試官描述了解決此問題的另一種方法的復雜性,這比較耗時,但最終占用的空間更少。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM