简体   繁体   English

为什么二和问题的hash解是O(n)?

[英]Why is the hash solution of the two sum problem O(n)?

Sorry to be a pain.对不起是一个痛苦。 I know it's a classic and I have checked, but I still can't understand why the time cost is O(n).知道很经典也查过了,但是还是不明白为什么时间成本是O(n)。

Here's my code.这是我的代码。

def two_sum(L, sum):
    targets = {}
    for i in range(len(L)):
        if L[i] in targets:
            return (targets[L[i]], i)
        else: targets[sum - L[i]] = i

While I get that L is only iterated over once and that the value look up for a given key is O(1), isn't the search for an actual key in a dict O(n)?虽然我知道 L 只被迭代一次并且查找给定键的值是 O(1),但在字典中搜索实际键不是 O(n) 吗? Doesn't that mean that for each value in L there is an O(n) look up cost to find if that value is key in the dict, making it a total of O(n^2)?这是否意味着对于 L 中的每个值,都有一个 O(n) 的查找成本来查找该值是否是字典中的键,从而使其总共为 O(n^2)?

Apologies if I'm being stupid but when I searched for an answer everyone just seems to be saying the lookup cost in a hash table is O(1), so it's only O(n) * O(1) = O(n).抱歉,如果我是愚蠢的,但当我搜索答案时,每个人似乎都在说 hash 表中的查找成本是 O(1),所以它只是 O(n) * O(1) = O(n) .

Edit: Just to clarify, the dict size in this problem grows with n.编辑:澄清一下,这个问题中的字典大小随 n 增长。

Ryan Wilson's link along with interjay's wisdom helped me realise how this works. Ryan Wilson 的联系以及 interjay 的智慧帮助我了解了这是如何运作的。

It doesn't iterate over a list of keys when you call key in dict, it just hashes the key and sees if it gets a valid answer!当您在 dict 中调用 key 时,它不会遍历键列表,它只是散列键并查看它是否得到有效答案!

Cheers everyone.大家干杯。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 两个总和运行时间O(n ^ 2)或O(n) - Two sum running time O(n^2) or O(n) 如何使用包含负整数的数组在 O(n) 时间复杂度中用 python 解决两个求和问题 - how to solve two sum problem with python in O(n) time complexity with an array that include negative integers python O(N^2)中的两个数字求和程序 - Two number Sum program in python O(N^2) O(n)求解最大差值和python 3.x的解决方案? - O(n) solution for finding maximum sum of differences python 3.x? 为什么此O(n ^ 2)解决方案比O(n)解决方案工作更快? - Why does this O(n^2) solution work faster than the O(n) solution? 我的解决方案是O(n ^ 2)吗,如果是,为什么它的运行速度与O(n)解决方案相同 - Is my solution O(n^2), if so, why is it running the same speed as O(n) solution 为什么IPython`%timeit`会给O(n)解决方案带来更慢的时间? - Why does IPython `%timeit` yield a slower time for an O(n) solution? 如何解决时间复杂度为 O(nlogn) 或 O(n) 的 python 中的对和问题? - How to solve Pair sum Problem in python with time complexity of O(nlogn) or O(n)? “三和”问题空间复杂度 - 为什么是 O(n)? - "Three sums" problem space complexity - Why is it O(n)? LeetCode“油漆屋”问题:尽管有O(N)解决方案,但超过了时间限制? - LeetCode “Paint House” problem: time limit exceeded despite O(N) solution?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM