题目:
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: TrueExplanation:123451239512In 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: FalseExplanation: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]
.
分析:
矩阵,可以归结到多维数组来进行分析。
考察多维数组操作。 但是不明白为什么限定元素边界为0-99.
在循环体中,需要注意return continue和break的区别:
return直接从函数中返回;
continue终止当前循环,从下一次循环开始执行;
break从循环中跳出。
第一次提交:
class Solution { public boolean isToeplitzMatrix(int[][] matrix) { int m,n; m = matrix.length; n = matrix[0].length; //int i =0; for(int j=0; j
结果:
Run Code Status: Time Limit ExceededRun Code Result:Your input[[1,2,3,4],[5,1,2,3],[9,5,1,2]]Your answerExpected answertrueRuntime: N/A
分析:
看来n的平方阶的算法不可行。
但m*n的时间复杂度看来是必须的,因为至少要遍历一遍矩阵,才能确定。
一个未完成的中间版本,原本打算使用一维数组代替二维数组,但后来发现没有本质区别。
class Solution { public boolean isToeplitzMatrix(int[][] matrix) { int m = matrix.length; int n = matrix[0].length; int[] array = new int[m*n]; /*for(int i=0; i<400; i++) { array[i] = -1; }*/ for(int i=0; i
查看了hint, 找到了解题关键: 每一个元素的特征:与左上角的元素相同。
class Solution { public boolean isToeplitzMatrix(int[][] matrix) { int m= matrix.length; int n= matrix[0].length; for(int i=0; i
结果:
Submission Result: Wrong Answer Input: [[1,2],[2,2]]Output: trueExpected: false
修改后再次提交:
class Solution { public boolean isToeplitzMatrix(int[][] matrix) { int m= matrix.length; int n= matrix[0].length; for(int i=0; i
结果:
Submission Result:
分析:
这道题找到正确思路前看了一下提示。之前没有找到正确的思路。