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; } }
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://specialneedsforspecialkids.com/yun/71192.html
摘要:題目詳情如果一個矩陣的每一條斜對角線左上到右下上的元素都相等,則我們稱它為托普利茲矩陣。現(xiàn)在輸入一個大小的矩陣,如果它是一個托普利茲矩陣,則返回,如果不是,返回。 題目詳情 matrix is Toeplitz if every diagonal from top-left to bottom-right has the same element.Now given an M x N ...
摘要:題目鏈接題目分析拓普利茲矩陣,應(yīng)該不用多說了。要求自己的右下和左上元素值相等。思路拿當前行的前位,與下一行的位對比即可。用這個方法會重復(fù)較多值,有優(yōu)化空間。最終代碼若覺得本文章對你有用,歡迎用愛發(fā)電資助。 766. Toeplitz Matrix 題目鏈接 766. Toeplitz Matrix 題目分析 拓普利茲矩陣,應(yīng)該不用多說了。 要求自己的右下和左上元素值相等。 思路 拿當前...
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...
摘要:兩種方法,轉(zhuǎn)置鏡像法和公式法。首先看轉(zhuǎn)置鏡像法原矩陣為轉(zhuǎn)置后水平鏡像翻轉(zhuǎn)后所以,基本的思路是兩次遍歷,第一次轉(zhuǎn)置,第二次水平鏡像翻轉(zhuǎn)變換列坐標。公式法是應(yīng)用了一個翻轉(zhuǎn)的公式如此翻轉(zhuǎ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...
閱讀 1267·2023-04-25 23:22
閱讀 1668·2023-04-25 20:04
閱讀 2643·2021-11-22 15:24
閱讀 2801·2021-11-11 16:54
閱讀 1879·2019-08-30 14:03
閱讀 1480·2019-08-29 16:35
閱讀 1700·2019-08-26 10:29
閱讀 2643·2019-08-23 18:01