766. 托普利茨矩阵

https://leetcode-cn.com/problems/toeplitz-matrix/

解法一:

遍历整个矩阵, 看每个元素[i,j]的右下方元素[i+1,j+1]是否与其相等即可

class Solution {
public:
    bool isToeplitzMatrix(vector<vector<int>>& matrix) {
        bool flag = true; //标志位
        int m = matrix.size(); //行数
        int n = matrix[0].size(); //列数
        for (int i = 0; i < m-1; i++) {
            for (int j = 0; j < n-1; j++) {
                if (matrix[i][j] != matrix[i+1][j+1]) //若发现不满足,标志位置0
                    flag = false;
            }
        }
        return flag;
    }
};

解法二:(进阶)

题目要求每次只读入一行,观察可知,自上而下,每行向右平移了一位。掐头去尾比较上下两行

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

最后更新于