|
| 1 | +# 766. Toeplitz Matrix |
| 2 | + |
| 3 | +**<font color=red>难度: Easy</font>** |
| 4 | + |
| 5 | +## 刷题内容 |
| 6 | + |
| 7 | +> 原题连接 |
| 8 | +
|
| 9 | +* https://leetcode.com/problems/toeplitz-matrix/description/ |
| 10 | + |
| 11 | +> 内容描述 |
| 12 | +
|
| 13 | +``` |
| 14 | +A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same element. |
| 15 | +
|
| 16 | +Now given an M x N matrix, return True if and only if the matrix is Toeplitz. |
| 17 | + |
| 18 | +
|
| 19 | +Example 1: |
| 20 | +
|
| 21 | +Input: |
| 22 | +matrix = [ |
| 23 | + [1,2,3,4], |
| 24 | + [5,1,2,3], |
| 25 | + [9,5,1,2] |
| 26 | +] |
| 27 | +Output: True |
| 28 | +Explanation: |
| 29 | +In the above grid, the diagonals are: |
| 30 | +"[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]". |
| 31 | +In each diagonal all elements are the same, so the answer is True. |
| 32 | +Example 2: |
| 33 | +
|
| 34 | +Input: |
| 35 | +matrix = [ |
| 36 | + [1,2], |
| 37 | + [2,2] |
| 38 | +] |
| 39 | +Output: False |
| 40 | +Explanation: |
| 41 | +The diagonal "[1, 2]" has different elements. |
| 42 | +
|
| 43 | +Note: |
| 44 | +
|
| 45 | +matrix will be a 2D array of integers. |
| 46 | +matrix will have a number of rows and columns in range [1, 20]. |
| 47 | +matrix[i][j] will be integers in range [0, 99]. |
| 48 | +
|
| 49 | +Follow up: |
| 50 | +
|
| 51 | +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? |
| 52 | +What if the matrix is so large that you can only load up a partial row into the memory at once? |
| 53 | +``` |
| 54 | + |
| 55 | +## 解题方案 |
| 56 | + |
| 57 | +> 思路 1 |
| 58 | +******- 时间复杂度: O(N^2)******- 空间复杂度: O(1)****** |
| 59 | + |
| 60 | + |
| 61 | +遍历每个元素,如果它与其右下角元素不相等,那么返回False |
| 62 | + |
| 63 | +beats 100% |
| 64 | + |
| 65 | +```python |
| 66 | +class Solution(object): |
| 67 | + def isToeplitzMatrix(self, matrix): |
| 68 | + """ |
| 69 | + :type matrix: List[List[int]] |
| 70 | + :rtype: bool |
| 71 | + """ |
| 72 | + if not matrix or len(matrix) == 0: |
| 73 | + return True |
| 74 | + row = len(matrix) |
| 75 | + col = len(matrix[0]) if row else 0 |
| 76 | + |
| 77 | + for i in range(row): |
| 78 | + for j in range(col): |
| 79 | + if i + 1 <= row - 1 and j + 1 <= col - 1 and matrix[i][j] != matrix[i+1][j+1]: |
| 80 | + return False |
| 81 | + return True |
| 82 | +``` |
| 83 | + |
| 84 | +1行版本 |
| 85 | + |
| 86 | +```python |
| 87 | +class Solution(object): |
| 88 | + def isToeplitzMatrix(self, matrix): |
| 89 | + """ |
| 90 | + :type matrix: List[List[int]] |
| 91 | + :rtype: bool |
| 92 | + """ |
| 93 | + return all(r == 0 or c == 0 or matrix[r-1][c-1] == val for r, row in enumerate(matrix) for c, val in enumerate(row)) |
| 94 | +``` |
0 commit comments