algorithm - 从两个长度为 n 的数字序列中找出所有可能的和,并在 O(n) 时间内将它们插入到哈希表中?

标签 algorithm hashtable time-complexity pseudocode

所以我要解决的问题如下:

The input is a sequence of n numbers {x1, x2, . . . , xn}, another sequence of n numbers {y1, y2, . . . , yn}, and a number z. Your algorithm should determine whether or not z ∈ {xi + yj | 1 ≤ i, j ≤ n}. You should use universal hashing families, and your algorithm should run in expected time O(n).

Provide justification that your algorithm is correct and runs in the required time. Be very clear about which theorems from class and/or the text you are using, and how.

到目前为止,我已经想出了这个算法来找到所有可能的和,将它们插入到哈希表中,然后搜索 z:

for (i in x; i++) {
    for (j in y; j++) {
        sum = xi + yj;
        insert_into_hash_table(T, sum);
    }
}

search_hash_table(T, z);

唯一的问题是这里最坏情况的时间是O(n^2)

如何在 O(n) 中执行此操作? =S

最佳答案

只需将所有Yi 放入map 即可。

现在一旦你有了Z:

 for all values from Xi
     find if Z - Xi os present in map

关于algorithm - 从两个长度为 n 的数字序列中找出所有可能的和,并在 O(n) 时间内将它们插入到哈希表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19915793/

相关文章:

algorithm - 递归如何突破第一个递归快速排序调用?

c# - 将较小的 n 维数组放入较大数组的最快方法(二维图形类比 : paint rectangle on canvas)

algorithm - 是否存在复杂度为 O(log n) 而 power(2, f) 不在 O(n) 中的函数

python - 从 Python 列表中选择三个不同的值

algorithm - 散列冲突 (CLRS)

c++ - 类(C++)中通用查找函数的返回值冲突,返回什么?

c# - 关于语法错误的子串,这个事实是真的吗?

algorithm - 比较两个数字的时间复杂度

ios - NSHashTable weakObjectsHashTable – 添加的对象未归零

java - 图和渐近分析之间的差异以比较算法的运行时间