【发布时间】: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