【问题标题】:How to determine if the time complexity is O(m + n) or O(Math.max(m, n))如何确定时间复杂度是 O(m + n) 还是 O(Math.max(m, n))
【发布时间】:2017-07-25 00:56:31
【问题描述】:

我正在查看这段代码,但我很难理解它是 O(m + n) 而不是 O(Math.max(m, n))。还是 O(Math.max(m, n)) 下的 O(m + n) 无论如何?

 int i = 0, j = 0, res = 0;
    while (i < houses.length) {
        while (j < heaters.length - 1
            && Math.abs(heaters[j + 1] - houses[i]) <= Math.abs(heaters[j] - houses[i])) {
            j++;
        }
        res = Math.max(res, Math.abs(heaters[j] - houses[i]));
        i++;
    }

CTCI 上有一个例子,函数返回一个 n 大小的数组。它说,由于 n > logn,在计算大 O 时,由于堆栈调用导致的 log(n) 空间复杂度相形见绌,导致总体上为 O(n)。这个例子中没有提到 O(n + logn)(好奇的人是 4.4)。

任何解释将不胜感激!

【问题讨论】:

  • 简单来说,m + n &lt;= Math.Max(m,n) + Math.Max(m,n) = O(Math.Max(m,n));因此结果。

标签: java performance time time-complexity space-complexity


【解决方案1】:

正如您已经猜到的那样,在 Big-O-Notation 下,两者相同

m + nmax(m, n) 这两个函数都是 集合 O(m + n) = O(max(m, n) 的元素。


让我们算一下:

m + n &lt;= max(m, n) + max(m, n) = 2 * max(m, n)max(m, n) &lt;= m + n 只要min(m, n) &gt;= 0 (但是m, n &gt;= 0 已经)

所以两个函数都受另一个函数的限制(加上一个常数因子),因此O(m + n)O(max(m, n)),集合是相等的。

这是正式的(一维)定义(来自Wikipedia):


直观地说,它也有意义,因为这两个函数只是意味着两个变量的线性增长,仅此而已。


[...] 总体结果为 O(n)。没有提到 O(n + logn) [...]

我不确定这是否是一个问题。请注意,这两个集合再次与 n &lt;= n + log(n)n + log(n) &lt;= n + n = 2 * n 相同,linear in n

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-21
    • 2019-06-17
    • 2019-12-13
    • 2020-05-30
    • 1970-01-01
    相关资源
    最近更新 更多