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
2
3
4
5
6
7
8
9
10
11
Input:
matrix = [
[1,2,3,4],
[5,1,2,3],
[9,5,1,2]
]
Output: True
Explanation:
In the above grid, the diagonals are:
"[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]".
In each diagonal all elements are the same, so the answer is True.

Example 2:

1
2
3
4
5
6
7
8
Input:
matrix = [
[1,2],
[2,2]
]
Output: False
Explanation:
The diagonal "[1, 2]" has different elements.

Note:

  1. matrix will be a 2D array of integers.

  2. matrix will have a number of rows and columns in range [1, 20].

  3. matrix[i][j] will be integers in range [0, 99].

Follow up:

  1. 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?
  2. 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
2
3
4
5
6
7
class Solution:
def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool:
for i in range(len(matrix) - 1):
for j in range(len(matrix[0]) - 1):
if matrix[i][j] != matrix[i + 1][j + 1]:
return False
return True

解法2:

1
2
3
4
5
6
class Solution:
def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool:
for row in range(len(matrix) - 1):
if matrix[row][:-1] != matrix[row + 1][1:]:
return False
return True