构建哈希表或字典 - 复杂性

时间:2014-03-28 10:47:45

标签: algorithm dictionary hashtable subset-sum

刚刚遇到这个问题:

Sub-set sum problem : Finding the count of two pairs of numbers in a given array whose sum is equal to a given number

例如:给定和为9且数组为{0,1,2,7,13} => O / P是1对(2和7)

似乎可以在O(n) 中实现(构建一个哈希表或字典,迭代给定数组的每个元素并从给定的总和中减去,检查结果数字是否可以实现)在数组中)

显然,迭代遍历数组的每个元素需要O(n)次。

My question is what is the time complexity and the space complexity for building the hash-table or the dictionary ?

注1:我的猜测是构建哈希表或字典的O(n),我们必须遍历数组中的每个元素。的 Is this correct ?

注2:那么,复杂度是O(n)+ O(n)= 2 * O(n)对吗? (但答案似乎只是O(n))

2 个答案:

答案 0 :(得分:2)

你的猜测是正确的。

哈希表的时间复杂度和空间复杂度与O(n)相同。

正如您所解释的那样,因为您需要将所有元素存储在哈希表中,这需要O(n)时间复杂度和O(N)空间复杂度。

答案 1 :(得分:2)

似乎时间复杂度为O(n),而不是O(n) + O(n) = 2 * O(n)

要在哈希表中插入元素是常量操作,因此需要花费O(1)时间,并且您在此处执行操作n时间,因此它将是O(n) * O(1)

所以最终会是O(n)

Data Structure with Time & Space Complexity.