LeetCode——766. Toeplitz Matrix [Simple]——Analysis and Code (Java)

LeetCode——766. Toeplitz Matrix[Simple]——Analysis and Code [Java]

1. Topic

Give you a matrix of mxn. If this matrix is ​​a Toplitz matrix, return true; otherwise, return false.
If the elements on each diagonal from the upper left to the lower right of the matrix are the same, then the matrix is ​​a Toplitz matrix.

Example 1:

输入:matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]
输出:true
解释:
在上述矩阵中, 其对角线为: 
"[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]"。 
各条对角线上的所有元素均相同, 因此答案是 True 。

Example 2:

输入:matrix = [[1,2],[2,2]]
输出:false
解释:
对角线 "[1, 2]" 上的元素不同。

prompt:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 20
  • 0 <= matrix[i][j] <= 99

Advanced:

  • What if the matrix is ​​stored on disk and the memory is so limited that only one row of the matrix can be loaded into the memory at a time?
  • What if the matrix is ​​so large that only an incomplete row can be loaded into memory at a time?

Source: LeetCode (LeetCode)
Link: https://leetcode-cn.com/problems/toeplitz-matrix
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Two, analysis and code

1. Direct comparison

(1) Thinking

According to the meaning of the question, directly compare whether the numbers on the diagonal are equal line by line.

(2) Code

class Solution {
    
    
    public boolean isToeplitzMatrix(int[][] matrix) {
    
    
        int n = matrix.length, m = matrix[0].length;
        for (int i = 1; i < n; i++)
            for (int j = 1; j < m; j++)
                if (matrix[i - 1][j - 1] != matrix[i][j])
                    return false;
        return true;
    }
}

(3) Results

Execution time: 1 ms, beating 100.00% of users
in all Java submissions ; memory consumption: 38.7 MB, beating 37.44 users in all Java submissions.

Three, other

Advanced question 1: You can convert the matrix row by row into a one-dimensional array and load it into the memory. When reading a new row, compare each element in sequence.
Advanced problem 2: Divide the matrix into several sub-matrices, and ensure that there is at least row or column overlap between the sub-matrices, and then judge in turn.

Guess you like

Origin blog.csdn.net/zml66666/article/details/114234860