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.
ExampleExample 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.
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
摘要:题目详情如果一个矩阵的每一条斜对角线左上到右下上的元素都相等,则我们称它为托普利兹矩阵。现在输入一个大小的矩阵,如果它是一个托普利兹矩阵,则返回,如果不是,返回。 题目详情 matrix is Toeplitz if every diagonal from top-left to bottom-right has the same element.Now given an M x N ...
摘要:题目链接题目分析拓普利兹矩阵,应该不用多说了。要求自己的右下和左上元素值相等。思路拿当前行的前位,与下一行的位对比即可。用这个方法会重复较多值,有优化空间。最终代码若觉得本文章对你有用,欢迎用爱发电资助。 766. Toeplitz Matrix 题目链接 766. Toeplitz 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...
摘要:两种方法,转置镜像法和公式法。首先看转置镜像法原矩阵为转置后水平镜像翻转后所以,基本的思路是两次遍历,第一次转置,第二次水平镜像翻转变换列坐标。公式法是应用了一个翻转的公式如此翻转四次即可。二者均可,并无分别。 Problem You are given an n x n 2D matrix representing an image.Rotate the image by 90 de...
摘要:把矩阵所有零点的行和列都置零,要求不要额外的空间。对于首行和首列的零点,进行额外的标记即可。这道题我自己做了四遍,下面几个问题需要格外注意标记首行和首列时,从到遍历时,若有零点,则首列标记为从到遍历,若有零点,则首行标记为。 Problem Given a m x n matrix, if an element is 0, set its entire row and column t...
阅读 1235·2023-04-25 23:22
阅读 1608·2023-04-25 20:04
阅读 2609·2021-11-22 15:24
阅读 2785·2021-11-11 16:54
阅读 1850·2019-08-30 14:03
阅读 1459·2019-08-29 16:35
阅读 1630·2019-08-26 10:29
阅读 2599·2019-08-23 18:01