Skip to content

Commit 06a7b4f

Browse files
refactor 766
1 parent 25cbe90 commit 06a7b4f

File tree

1 file changed

+34
-66
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+34
-66
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,72 +1,40 @@
11
package com.fishercoder.solutions;
22

3-
/**766. Toeplitz Matrix
4-
*
5-
* A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same element.
6-
7-
Now given an M x N matrix, return True if and only if the matrix is Toeplitz.
8-
9-
Example 1:
10-
11-
Input: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]
12-
Output: True
13-
Explanation:
14-
1234
15-
5123
16-
9512
17-
18-
In the above grid, the diagonals are "[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]",
19-
and in each diagonal all elements are the same, so the answer is True.
20-
21-
Example 2:
22-
23-
Input: matrix = [[1,2],[2,2]]
24-
Output: False
25-
Explanation:
26-
The diagonal "[1, 2]" has different elements.
27-
28-
Note:
29-
30-
matrix will be a 2D array of integers.
31-
matrix will have a number of rows and columns in range [1, 20].
32-
matrix[i][j] will be integers in range [0, 99].
33-
34-
*/
353
public class _766 {
36-
public static class Solution1 {
37-
public boolean isToeplitzMatrix(int[][] matrix) {
38-
int m = matrix.length;
39-
int n = matrix[0].length;
40-
int i = 0;
41-
int j = 0;
42-
int sameVal = matrix[i][j];
43-
while (++i < m && ++j < n) {
44-
if (matrix[i][j] != sameVal) {
45-
return false;
46-
}
47-
}
48-
49-
for (i = 1, j = 0; i < m; i++) {
50-
int tmpI = i;
51-
int tmpJ = j;
52-
sameVal = matrix[i][j];
53-
while (++tmpI < m && ++tmpJ < n) {
54-
if (matrix[tmpI][tmpJ] != sameVal) {
55-
return false;
56-
}
57-
}
58-
}
59-
for (i = 0, j = 1; j < n; j++) {
60-
int tmpJ = j;
61-
int tmpI = i;
62-
sameVal = matrix[tmpI][tmpJ];
63-
while (++tmpI < m && ++tmpJ < n) {
64-
if (matrix[tmpI][tmpJ] != sameVal) {
65-
return false;
66-
}
4+
public static class Solution1 {
5+
public boolean isToeplitzMatrix(int[][] matrix) {
6+
int m = matrix.length;
7+
int n = matrix[0].length;
8+
int i = 0;
9+
int j = 0;
10+
int sameVal = matrix[i][j];
11+
while (++i < m && ++j < n) {
12+
if (matrix[i][j] != sameVal) {
13+
return false;
14+
}
15+
}
16+
17+
for (i = 1, j = 0; i < m; i++) {
18+
int tmpI = i;
19+
int tmpJ = j;
20+
sameVal = matrix[i][j];
21+
while (++tmpI < m && ++tmpJ < n) {
22+
if (matrix[tmpI][tmpJ] != sameVal) {
23+
return false;
24+
}
25+
}
26+
}
27+
for (i = 0, j = 1; j < n; j++) {
28+
int tmpJ = j;
29+
int tmpI = i;
30+
sameVal = matrix[tmpI][tmpJ];
31+
while (++tmpI < m && ++tmpJ < n) {
32+
if (matrix[tmpI][tmpJ] != sameVal) {
33+
return false;
34+
}
35+
}
36+
}
37+
return true;
6738
}
68-
}
69-
return true;
7039
}
71-
}
7240
}

0 commit comments

Comments
 (0)