for 循环内 HashMap 插入和检索的时间复杂度是多少?
我已经为一个应用程序编写了这段代码,但我很难确定它是否比旧代码更好(旧代码在每个值中使用一个带有 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);
}
}
}
I have written this code for an application but I'm having difficulty figuring out if its better than the legacy code (legacy code used one hashmap with List in every value). From what I understand, since Java 8 the insertion and retrieval from a Hashmap is O(log n) and the for loop is O(n) in my case. Am I correct in assuming that the time complexity here would be 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);
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
遍历元素的 for 循环是 O(n),遍历 HashMap 是 O(1),最终答案是 O(n),请参阅 这里。
It's O(n) for traversing the for loop for the elements and O(1) for the HashMap, the final answer is O(n), see more in here.