LeetCode 题解工作台

托普利茨矩阵

给你一个 m x n 的矩阵 matrix 。如果这个矩阵是托普利茨矩阵,返回 true ;否则,返回 false 。 如果矩阵上每一条由左上到右下的对角线上的元素都相同,那么这个矩阵是 托普利茨矩阵 。 示例 1: 输入: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,…

category

2

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·matrix

bolt

答案摘要

根据题目描述,托普利茨矩阵的特点是:矩阵中每个元素都与其左上角的元素相等。因此,我们只需要遍历矩阵中的每个元素,检查它是否与左上角的元素相等即可。 时间复杂度 $O(m \times n)$,其中 和 分别是矩阵的行数和列数。空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·matrix 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个 m x n 的矩阵 matrix 。如果这个矩阵是托普利茨矩阵,返回 true ;否则,返回 false

如果矩阵上每一条由左上到右下的对角线上的元素都相同,那么这个矩阵是 托普利茨矩阵

 

示例 1:

输入:matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]
输出:true
解释:
在上述矩阵中, 其对角线为: 
"[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]"。 
各条对角线上的所有元素均相同, 因此答案是 True 。

示例 2:

输入:matrix = [[1,2],[2,2]]
输出:false
解释:
对角线 "[1, 2]" 上的元素不同。

 

提示:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 20
  • 0 <= matrix[i][j] <= 99

 

进阶:

  • 如果矩阵存储在磁盘上,并且内存有限,以至于一次最多只能将矩阵的一行加载到内存中,该怎么办?
  • 如果矩阵太大,以至于一次只能将不完整的一行加载到内存中,该怎么办?
lightbulb

解题思路

方法一:一次遍历

根据题目描述,托普利茨矩阵的特点是:矩阵中每个元素都与其左上角的元素相等。因此,我们只需要遍历矩阵中的每个元素,检查它是否与左上角的元素相等即可。

时间复杂度 O(m×n)O(m \times n),其中 mmnn 分别是矩阵的行数和列数。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
class Solution:
    def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool:
        m, n = len(matrix), len(matrix[0])
        for i in range(1, m):
            for j in range(1, n):
                if matrix[i][j] != matrix[i - 1][j - 1]:
                    return False
        return True
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    The candidate efficiently checks diagonals without redundant comparisons.

  • question_mark

    The candidate understands edge case handling and matrix traversal.

  • question_mark

    The candidate optimizes the solution when applicable, reducing unnecessary checks.

warning

常见陷阱

外企场景
  • error

    Failing to correctly handle matrices with a single row or column.

  • error

    Overlooking the need for diagonal comparison from the second row and column.

  • error

    Not optimizing for edge cases where the matrix size is small, such as 1x1 matrices.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Consider matrices of larger sizes, pushing the time complexity boundaries.

  • arrow_right_alt

    Solve this problem in a non-iterative manner, exploring matrix transformations.

  • arrow_right_alt

    Modify the problem to check for Toeplitz properties in other directions or shapes.

help

常见问题

外企场景

托普利茨矩阵题解:数组·matrix | LeetCode #766 简单