Check in (5)

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

It's still quite a simple question, but it always feels not as clever as the solution: the
solution shows that it only needs to compare whether this element is equal to the element in its upper left corner, that is, it uses the transitivity of equality.
My code:

class Solution {
    
    
public:
    bool isToeplitzMatrix(vector<vector<int>>& matrix) {
    
    
        int n=matrix.size();
        int m=matrix[0].size();
        for(int i=0;i<m-1;i++){
    
    
            int k=1,j=i;
            while(j<m&&k<n){
    
    
                if(matrix[k++][j++]==matrix[0][i])
                continue;
                else return false;
            }
        }
        for(int i=1;i<n-1;i++){
    
    
            int k=2,j=i;
            while(j<m&&k<n){
    
    
                if(matrix[k++][j++]==matrix[i][0])
                continue;
                else return false;
            }
        }
        return true;
    }
};

Concise version:

class Solution {
    
    
public:
    bool isToeplitzMatrix(vector<vector<int>>& matrix) {
    
    
        int m = matrix.size(), n = matrix[0].size();
        for (int i = 1; i < m; i++) {
    
    
            for (int j = 1; j < n; j++) {
    
    
                if (matrix[i][j] != matrix[i - 1][j - 1]) {
    
    
                    return false;
                }
            }
        }
        return true;
    }
};

Comparing the code of the problem solution, it is indeed a bit more complicated, but the time complexity is the same, so I lost the space complexity (×), and the space complexity should also be the same, but it is not so clear to write. \

Wisdom tooth pain is very severe. At this time, when a girl cares about me, I fall in love with her/doge.
Okay, I hope tomorrow is another day for planting trees.

Guess you like

Origin blog.csdn.net/weixin_47741017/article/details/114156675