Leetcode_Array --766. Toeplitz Matrix [easy]

A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same element.
一个矩阵如果每条对角线从左上角到右下角都是相同的元素,我们称它为Toeplitz矩阵
Now given an M x N matrix, return True if and only if the matrix is Toeplitz.
现给定一个M*N的矩阵,当它为Toeplitz矩阵的时候,返回True

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.

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?
1、如果矩阵被存储在磁盘上,内存最多存放矩阵的一行,怎么做?
2、What if the matrix is so large that you can only load up a partial row into the memory at once?
2、如果矩阵非常大,你只能存储一行的部分进内存,怎么做?

Solution:
这个算法需要找到判定的规律,最大的破绽就是矩阵的左下角和右上角的元素是不需要判断的,因为这两个数都是唯一的;另外一个规律就是,要想判定各条对角线上元素相等,那么只需要 matrix[i][j] = matrix[i+1][j+1] ,所以在实际操作过程中,我们遍历的矩阵维度其实是(M-1)*(N-1)维,就是去掉了矩阵的最下面一行和最后面一列。

Python

class Solution:
    def isToeplitzMatrix(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: 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
C++

class Solution {
public:
    bool isToeplitzMatrix(vector<vector<int>>& matrix) {
        for (int i = 0;i<matrix.size()-1;i++){
            for (int j = 0;j<matrix[0].size()-1;j++){
                if(matrix[i][j] != matrix[i+1][j+1]){
                    return false;
                }
            }
        }
        return true;
        
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值