Leetcode 766. Toeplitz Matrix (Java)
2018-04-01 23:46
381 查看
问题描述
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 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.
Note:
matrix will be a 2D array of integers.
matrix will have a number of rows and columns in range [1, 20].
matrix[i][j] will be integers in range [0, 99].
解决方案
package test ; import java.lang.* ; import java.util.*; class Solution { public boolean isToeplitzMatrix(int[][] matrix) { int rows = matrix.length ; //行数 int cols = matrix[0].length ; //列数 boolean flag = true ; int r = rows - 1, c = 1 ; //当前对角线的起始位置 //更新行递减的对角线 while(r >= 0 && flag == true){ for(int i = r, j = 0; i < rows - 1 && j < cols - 1 && flag == true; i ++, j ++){ if(matrix[i][j] != matrix[i + 1][j + 1]){ flag = false ; return flag ; } } r -- ; } //更新列递增的对角线 while(c <= cols - 1 && flag == true){ for(int i = 0, j = c; i < rows - 1 && j < cols - 1 && flag ==true; i ++, j ++){ if(matrix[i][j] != matrix[i + 1][j + 1]){ flag = false ; return flag ; } } c ++ ; } return true ; } } public class Test{ public static void main(String[] args){ Solution s = new Solution() ; int[][] ma = {{1,2,3,4}, {5,1,2,3}, {9,5,1,0}} ; System.out.println(s.isToeplitzMatrix(ma)) ; } }
我自己最先想到的方法就是暴力解决,逐对角线比较该上的元素是否相等
Java获得二维数组行数和列数的方法:
int rows = matrix.length ; //行数 int cols = matrix[0].length ; //列数
在Discuss里面第一个给出的答案很精简,贴在这里供瞻仰~
class Solution { public boolean isToeplitzMatrix(int[][] matrix) { for (int i = 0; i < matrix.length - 1; i++) { for (int j = 0; j < matrix[i].length - 1; j++) { if (matrix[i][j] != matrix[i + 1][j + 1]) return false; } } return true; } }
该代码的思想就是逐行比较每个元素与自己对角线上的下一个元素是否相等(二维数matrix[0][cols-1]和matrix[rows-1][0]不用比较,因为该对角线上只有一个元素),一旦出现不相等就return false,否则return true。
相关文章推荐
- LeetCode 766. Toeplitz Matrix
- LeetCode766. Toeplitz Matrix
- LeetCode 766. Toeplitz Matrix
- LeetCode - 766. Toeplitz Matrix
- 766. Toeplitz Matrix (leetcode)
- 【LeetCode】766. Toeplitz Matrix(Toeplitz矩阵)
- <easy>LeetCode Problem -- 766. Toeplitz Matrix
- LeetCode 73 — Set Matrix Zeroes(C++ Java Python)
- [LeetCode][Java] Set Matrix Zeroes
- [Leetcode] Set Matrix Zeroes (Java)
- leetcode:Spiral Matrix 【Java】
- 【LeetCode-面试算法经典-Java实现】【070-Set Matrix Zeroes(矩阵置零)】
- [leetcode]74. Search a 2D Matrix(Java)
- Java for LeetCode 073 Set Matrix Zeroes
- 【leetcode】74. Search a 2D Matrix【java】
- leetcode解题之 Search a 2D Matrix java 版(在二维矩阵中查找)
- LeetCode – Search a 2D Matrix (Java)
- Java for LeetCode 059 Spiral Matrix II
- leetcode JAVA Set Matrix Zeroes 难度系数3 3.24
- LeetCode-542. 01 Matrix (JAVA)零一矩阵