题目
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]
.
答题
思路一
1234
5123
9512
多维数组中
-
1
元素的下标为00
、11
、22
-
5
元素的下标为10
、21
-
2
元素的下标为01
、12
、23
-
3
元素的下标为02
、13
规律我想大家都明白了。
public boolean isToeplitzMatrix(int[][] matrix) {
int xSize = matrix.length;
if (xSize <= 1) {
return true;
}
int[] temp = matrix[0];
int ySize = temp.length;
if (ySize <= 1) {
return true;
}
boolean result = true;
for (int x = 0; x < xSize - 1; x++) {
result = result & check(matrix, x, 0, xSize, ySize);
if (!result) {
return false;
}
}
for (int y = 0; y < ySize - 1; y++) {
result = result & check(matrix, 0, y, xSize, ySize);
if (!result) {
return false;
}
}
return true;
}
private boolean check(int[][] matrix, int x, int y, int xSize, int ySize) {
if (x > xSize - 1 || y > ySize - 1) {
return true;
}
if (x != 0 && y != 0) {
if (matrix[x][y] != matrix[x - 1][y - 1]) {
return false;
}
}
return check(matrix, x + 1, y + 1, xSize, ySize);
}
再精简代码
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;
}
思路二
1234
5123
9512
继续寻找规律,我们发现 9
和 4
是不需要比较的,那么我们去掉这两个数:
123
5123
512
第一行与最后一行的数组大小比其他行小1,且第一行元素等于第二行除去第一个元素的其他元素,以此类推。
public boolean isToeplitzMatrix(int[][] matrix) {
int m = matrix.length, n = matrix[0].length;
for (int i = 0; i < m - 1; i++) {
int[] arr1 = Arrays.copyOfRange(matrix[i], 0, n - 1), arr2 = Arrays.copyOfRange(matrix[i + 1], 1, n);
if (Arrays.equals(arr1, arr2)) {
continue;
} else
return false;
}
return true;
}