Daily LeetCode 766. Toeplitz Matri
https://leetcode.com/problems/toeplitz-matrix/
Easy
问题描述:
A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same element.
Now given an M x N
matrix, return True
if and only if the matrix is Toeplitz.
Example 1:
1 | Input: |
Example 2:
1 | Input: |
Note:
matrix
will be a 2D array of integers.matrix
will have a number of rows and columns in range[1, 20]
.matrix[i][j]
will be integers in range[0, 99]
.
Follow up:
- What if the matrix is stored on disk, and the memory is limited such that you can only load at most one row of the matrix into the memory at once?
- What if the matrix is so large that you can only load up a partial row into the memory at once?
题目分析:
题目给出了一个Toeplitz矩阵的概念,这种矩阵每一条从左上到右下的对角线上的元素都相等。
最简单的解法就是一一对比,从左上角开始遍历整个矩阵,若当前元素坐标为[i, j]
,那么对角线的下一个元素坐标为[i+1, j+1]
,当遇到不想等的元素时,返回False
即可。
第二种解法是将矩阵切片,给定矩阵:
$$
\left[\begin{matrix}
1&2&3&4\
2&1&2&3\
3&2&1&2\
4&3&2&1
\end{matrix}\right]
$$
我们可以观察到,只要第i
行的[:-1]
与第i+1
行的[1:]
相等,就能确保整个矩阵的每条正对角线都相等。
代码:
解法1:
1 | class Solution: |
解法2:
1 | class Solution: |