python - 收集雨水的时间复杂度

标签 python c++ arrays algorithm big-o

我一直在研究 problem 的不同算法在 Leetcode 上以 approach 1 开头.如果数组值是墙的高度,则该问题需要计算总水域面积(列宽 = 1)。

第一种方法找到每列左侧和右侧最大墙高的最小高度,如果列高度小于最小值,则将水添加到给定列的顶部。取最小值是因为这是收集到的水可以达到的最高值。要计算每边的最大值,需要对左侧和右侧进行 n-1 遍历。

我用 Python 编写代码,但这里是根据 Leetcode 上给出的解决方案用 C++ 编写的代码.问题不在于理解 C++,而是在代码之后解释的数学。

int trap(vector<int>& height)
{
    int ans = 0;
    int size = height.size();
    for (int i = 1; i < size - 1; i++) {
        int max_left = 0, max_right = 0;
        for (int j = i; j >= 0; j--) { //Search the left part for max bar size
            max_left = max(max_left, height[j]);
        }
        for (int j = i; j < size; j++) { //Search the right part for max bar size
            max_right = max(max_right, height[j]);
        }
        ans += min(max_left, max_right) - height[i];
    }
    return ans;
}

我不明白他们是如何达到时间复杂度 O(n^2) 的。我得到了 O(n^3)。

Index | Comparisons/Traversals
-------------------------------
  1   |            n
  2   |            n
  3   |            n
  4   |            n
  .   |            .
  .   |            .
  .   |            .
 n-1  |            n

此处执行的总操作为: n + 2n + 3n + 4n + n(n-1) + n^2

现在用等差级数公式 Sum = n * (a_1 + a_n)/2 得到here并粘贴在下面 Arithmetic series formulas

上面的总和最终会是:

Sum = n * [n + n(n-1)]/ 2 = n * [n + n^2- n)]/ 2 = (n^3)/2

这将给出 O(n^3)

我的推理有什么问题?它似乎是 O(n^2) 作为 GeeksForGeeks也指出了这一点。

最佳答案

问题出在这里:

The total operations performed here would be: n + 2n + 3n + 4n + n(n-1) + n^2

但是你的表的每一行只是 n,而不是 n, 2n, …, n^2

快速浏览一下,很明显您也正确地填写了表格:内部循环有 O(n) 个恒定时间步。

您所做的所有其他数学运算都是正确的,但无关紧要。总结 nn,你只是多个 n * n,当然是 n^2 ,不是 O(n^3)

关于python - 收集雨水的时间复杂度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50806043/

相关文章:

c++ - 具有不同对齐要求的不同类型的两个对象可以具有相同的对象表示吗?

c++ - vector resize()、push.back()、reserve() 方法

javascript - 在javascript中解析Json并获取键/值的最佳方法

python - 关于在 sqlalchemy session 中刷新对象

c++ - 静态类和继承

python - 运行时错误 : one of the variables needed for gradient computation has been modified by an inplace operation?

c# - 向数组添加元素

javascript - lodash _.findIndex 通过多个值

python - Pandas:如何根据 ID 和条件替换面板数据集中的列值

python - Python脚本不起作用?:播放声音,测量响应时间