【问题标题】:Time complexity for HashMap put/get inside for?HashMap put/get inside 的时间复杂度?
【发布时间】:2020-10-11 11:51:20
【问题描述】:

假设我有以下代码片段:

for(int i=0; i < n.length(); i++) {
    int aux = n[i];
    if(map.containsKey(aux)) {
        map.put(aux, map.get(aux)+1);
    } else {
        map.put(aux, 1);
    }
}

我的地图是 HashMap。 我知道 for 将是 O(n),然后 map 操作有 O(1),但是我在那里有三个 map 操作(containsKey、put 和 get)所以是 O(3n) 还是 O(n)?为什么?

【问题讨论】:

    标签: java algorithm hashmap time-complexity complexity-theory


    【解决方案1】:

    O(3N) 和 O(N) 将被视为 O(N)。


    我想,如果我没记错的话,也许getOrDefault() 是一个选项:

    for (int i = 0; i < n.length(); i++) {
        int aux = n[i];
    
        map.put(aux, map.getOrDefault(aux, 0) + 1);
    }
    

    你的时间和内存复杂度都是 O(N)。


    我认为另一个更易读的版本是:

    for (int i = 0; i < n.length(); i++) {
        int aux = n[i];
    
        map.put(aux, -~map.getOrDefault(aux, 0));
    }
    

    -~x 只是x + 1 (-~x = x + 1) 的按位运算。但是,您可以使用任何您觉得舒服的方式。


    感谢评论中的ciamej

    【讨论】:

    • O(3N) = O(N) 根据定义。
    • 嗯,其实应该是map.put(aux, map.getOrDefault(aux, 0) + 1);
    • 顺便说一句:我刚刚检查了您的个人资料。哇! 1,645 个答案,太棒了!继续努力吧! :)
    • 你确实帮助了很多人!即使他们中的大多数人只获得几票(甚至零票),这些答案也很重要。
    猜你喜欢
    • 2011-12-31
    • 2017-05-17
    • 2021-04-17
    • 2017-09-12
    • 1970-01-01
    • 1970-01-01
    • 2012-12-24
    • 2022-01-01
    • 1970-01-01
    相关资源
    最近更新 更多