我已經為一個應用程式撰寫了這段代碼,但我很難確定它是否比舊代碼更好(舊代碼使用一個哈希圖,每個值都帶有 List)。據我了解,由于 Java 8,從 Hashmap 的插入和檢索是 O(log n),而 for 回圈在我的例子中是 O(n)。我假設這里的時間復雜度為 O(n log n) 是否正確?
//complexity => O(n)
for (int i = 0; i < len; i ) {
String s = someList.get(i);
int someValue = someArray[i];
if (someCondition < 0) {
// complexity => O(log n)
if (hashmap1.containsKey(s)) {
//complexity => O(log n) O(log n) = O(log n)
hashmap1.put(s, hashmap1.get(s) someValue);
//complexity => O(log n) O(log n) = O(log n)
hashmap2.put(s, hashmap2.get(s) 1);
} else {
//complexity => O(log n)
hashmap1.put(s, someValue);
//complexity => O(log n)
hashmap2.put(s, 1);
}
}
}
uj5u.com熱心網友回復:
遍歷元素的 for 回圈是 O(n),而 HashMap 的遍歷是 O(1),最終答案是 O(n),請參見此處的更多資訊。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/437438.html
上一篇:方法的junit測驗