资讯专栏INFORMATION COLUMN

[LintCode] Toeplitz Matrix

xuxueli / 724人阅读

Problem

A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same element.

Now given an M x N matrix, return True if and only if the matrix is Toeplitz.

Example

Example 1:

Input: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]
Output: True
Explanation:
1234
5123
9512

In the above grid, the diagonals are "[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]", and 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.

Solution
public class Solution {
    /**
     * @param matrix: the given matrix
     * @return: True if and only if the matrix is Toeplitz
     */
    public boolean isToeplitzMatrix(int[][] matrix) {
        // Write your code here
        // DP? No.
        // New arrays? No.
        // Why? Because it"s too simple.
        int m = matrix.length;
        int n = matrix[0].length;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (i == 0 || j == 0) continue;
                if (matrix[i][j] != matrix[i-1][j-1]) return false;
            }
        }
        return true;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/71192.html

相关文章

  • leetcode 766 Toeplitz Matrix

    摘要:题目详情如果一个矩阵的每一条斜对角线左上到右下上的元素都相等,则我们称它为托普利兹矩阵。现在输入一个大小的矩阵,如果它是一个托普利兹矩阵,则返回,如果不是,返回。 题目详情 matrix is Toeplitz if every diagonal from top-left to bottom-right has the same element.Now given an M x N ...

    harriszh 评论0 收藏0
  • Leetcode PHP题解--D26 766. Toeplitz Matrix

    摘要:题目链接题目分析拓普利兹矩阵,应该不用多说了。要求自己的右下和左上元素值相等。思路拿当前行的前位,与下一行的位对比即可。用这个方法会重复较多值,有优化空间。最终代码若觉得本文章对你有用,欢迎用爱发电资助。 766. Toeplitz Matrix 题目链接 766. Toeplitz Matrix 题目分析 拓普利兹矩阵,应该不用多说了。 要求自己的右下和左上元素值相等。 思路 拿当前...

    heartFollower 评论0 收藏0
  • [LintCode] Kth Smallest Number in Sorted Matrix

    Problem Find the kth smallest number in at row and column sorted matrix. Example Given k = 4 and a matrix: [ [1 ,5 ,7], [3 ,7 ,8], [4 ,8 ,9], ] return 5 Challenge O(k log n), n is the maximal n...

    mgckid 评论0 收藏0
  • [LintCode/LeetCode] Rotate Image

    摘要:两种方法,转置镜像法和公式法。首先看转置镜像法原矩阵为转置后水平镜像翻转后所以,基本的思路是两次遍历,第一次转置,第二次水平镜像翻转变换列坐标。公式法是应用了一个翻转的公式如此翻转四次即可。二者均可,并无分别。 Problem You are given an n x n 2D matrix representing an image.Rotate the image by 90 de...

    BenCHou 评论0 收藏0
  • [LintCode/LeetCode/CC] Set Matrix Zeroes

    摘要:把矩阵所有零点的行和列都置零,要求不要额外的空间。对于首行和首列的零点,进行额外的标记即可。这道题我自己做了四遍,下面几个问题需要格外注意标记首行和首列时,从到遍历时,若有零点,则首列标记为从到遍历,若有零点,则首行标记为。 Problem Given a m x n matrix, if an element is 0, set its entire row and column t...

    zhangwang 评论0 收藏0

发表评论

0条评论

xuxueli

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<