【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 每日一题更新
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值