【问题标题】:Why O(n) takes longer than O(n^2)?为什么 O(n) 比 O(n^2) 花费更长的时间?
【发布时间】:2018-11-05 02:57:20
【问题描述】:

我有一个 LeetCode 问题:

给定一个 M x N 矩阵,当且仅当该矩阵是 Toeplitz 时才返回 True。

如果从左上角到右下角的每条对角线都具有相同的元素,则矩阵为Toeplitz。

我的解决方案是(Swift):

func isToeplitzMatrix(_ matrix: [[Int]]) -> Bool {
    if matrix.count == 1 { return true }

    for i in 0 ..< matrix.count - 1 {
        if matrix[i].dropLast() != matrix[i + 1].dropFirst() { return false }
    }

    return true
}

根据我对大 O 表示法的理解,我的算法的时间复杂度是 O(n),而 LeetCode 最佳答案的时间复杂度是 O(n^2)。

热门答案示例:

func isToeplitzMatrix(_ matrix: [[Int]]) -> Bool {
    for i in 0..<matrix.count-1 {
      for j in 0..<matrix[0].count-1 {
          if (matrix[i][j] != matrix[i+1][j+1]) {
              return false;
          }
      }
    }

     return true;
}

不过,我的算法需要 36 毫秒(根据 LeetCode),而最佳答案需要 28 毫秒。

当我注释掉 if matrix.count == 1 { return true } 时,它需要更多的时间来运行 - 56 毫秒。

【问题讨论】:

  • dropFirst() 和dropLast() 的时间复杂度是多少? != 在数组上的时间复杂度是多少?
  • 这里的n 是什么?矩阵中的行数或整数数?无论哪种方式,两段代码看起来都具有相同的复杂性(O(n) 表示整数数;或者O(n^2) 如果n 是行数,也是列数)。

标签: swift algorithm for-loop time-complexity big-o


【解决方案1】:

函数的时间复杂度也是 O(n^2),因为函数调用 dropLast 是 O(n)。

编辑: Rup 和 melpomene 也提到过,数组的比较也将复杂度提高到 O(n^2)。

此外,大 O 表示法描述了算法如何根据数据数量 n 进行扩展。为简洁起见,它去掉了任何常量。因此,如果输入数据足够小,O(1) 的算法可能会比 O(n^3) 的算法慢。

【讨论】:

猜你喜欢
  • 2019-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-24
  • 1970-01-01
  • 1970-01-01
  • 2019-12-09
相关资源
最近更新 更多