【LeetCode】766. Toeplitz Matrix 托普利茨矩阵(Easy)(JAVA)

【LeetCode】766. Toeplitz Matrix 托普利茨矩阵(Easy)(JAVA)

题目地址: https://leetcode.com/problems/toeplitz-matrix/

题目描述:

Given an m x n matrix, return true if the matrix is Toeplitz. Otherwise, return false.

A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same elements.

Example 1:

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:

Input: matrix = [[1,2],[2,2]]
Output: false
Explanation:
The diagonal "[1, 2]" has different elements.

Constraints:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 20
  • 0 <= matrix[i][j] <= 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?

题目大意

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

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

进阶:

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

解题方法

  1. 按照托普利茨矩阵遍历每次的对角线即可
  2. 进阶1 (如果矩阵存储在磁盘上,并且内存有限,以至于一次最多只能将矩阵的一行加载到内存中,该怎么办?):通过上一行计算出下一行的结果即可
  3. 进阶1 (如果矩阵太大,以至于一次只能将不完整的一行加载到内存中,该怎么办?):把一行分割,同时记录分割后这一行的内容和上一行前面的边界内容
class Solution {
    public boolean isToeplitzMatrix(int[][] matrix) {
        if (matrix.length == 0 || matrix[0].length == 0) return true;
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; (i + j) < matrix.length && j < matrix[0].length; j++) {
                if (matrix[i + j][j] != matrix[i][0]) return false;
            }
        }
        for (int i = 0; i < matrix[0].length; i++) {
            for (int j = 0; (i + j) < matrix[0].length && j < matrix.length; j++) {
                if (matrix[j][i + j] != matrix[0][i]) return false;
            }
        }
        return true;
    }
}

执行耗时:1 ms,击败了100.00% 的Java用户
内存消耗:38.6 MB,击败了47.69% 的Java用户

欢迎关注我的公众号,LeetCode 每日一题更新

猜你喜欢

转载自blog.csdn.net/qq_16927853/article/details/113928473