【问题标题】:Buiding a hash table or a dictionary - complexity构建哈希表或字典 - 复杂性
【发布时间】:2014-05-07 18:54:36
【问题描述】:

刚刚遇到这个问题:

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))

【问题讨论】:

    标签: algorithm dictionary hashtable subset-sum


    【解决方案1】:

    你猜对了。

    hashtable 的时间复杂度和空间复杂度是相同的 O(n)。

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

    【讨论】:

      【解决方案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.

      【讨论】:

      • 优秀的答案!很好解释。虽然它是一个 3 岁的问题,但这个答案只是很好地详细说明了它。谢谢! !
      猜你喜欢
      • 2016-11-03
      • 1970-01-01
      • 1970-01-01
      • 2013-12-29
      • 1970-01-01
      • 1970-01-01
      • 2016-03-31
      • 2019-04-17
      • 2015-10-11
      相关资源
      最近更新 更多