algorithm - 使用矩阵在 O(1) 时间内回答查询

标签 algorithm data-structures matrix

这是作业,我已经有了答案。我只是想了解它的样子,因为我无法想象它。

Suppose that we are given a sequence of n values x1, x2, ..., xn and seek to quickly answer repeated queries of the form: given i and j, find the smallest value in xi, . . . , xj .

问题是:

a) Design a data structure that uses O(n^2) space and answers queries in O(1) time.

根据 Skienna 的维基页面,答案是

Use an nxn matrix populated with the distance between the nodes at the two indices.

我知道 n x n 矩阵会给我们 n^2 空间,但我不明白这个矩阵是什么样的。

最佳答案

嗯...让我们举个例子:

对于值:3 5 4 2

矩阵将是:

3 3 3 2
3 5 4 2
3 4 4 2
2 2 2 2

矩阵总是symmetric :我们可以允许 j < i表示 xj..xi

这称为查找表。 (i, j) 处的每个值都等于 min(xi..xj)。这意味着,您预先计算您的正常函数将返回的值。

关于algorithm - 使用矩阵在 O(1) 时间内回答查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26079337/

相关文章:

c++ - 模数公式

javascript - 在 JavaScript 中构建模块化方法

java - 使用 Java 有效地将排序的 ArrayList 放入排序的数据结构中并找到小于 x 的数字数量

java - 为字典构建数据结构

python - 如何分析混淆矩阵?

python - Pandas 组合共享关联的行

c++ - 从字符串中删除计数大于或等于突发长度的相邻重复项

javascript - 计算数组中随机生成的元素?

java - ListNode解决方案需要说明

c++ - 如何在 Qt 中为矩阵类定义 [ ][ ] 运算符?