目录结构
1.题目
如果矩阵上每一条由左上到右下的对角线上的元素都相同,那么这个矩阵是 托普利茨矩阵 。
给定一个 M x N 的矩阵,当且仅当它是托普利茨矩阵时返回 True。
示例:
输入:
matrix = [
[1,2,3,4],
[5,1,2,3],
[9,5,1,2]
]
输出: True
解释:
在上述矩阵中, 其对角线为:
"[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]"。
各条对角线上的所有元素均相同, 因此答案是True。
输入:
matrix = [
[1,2],
[2,2]
]
输出: False
解释:
对角线"[1, 2]"上的元素不同。
说明:
- matrix 是一个包含整数的二维数组。
- matrix 的行数和列数均在 [1, 20]范围内。
- matrix[i][j] 包含的整数在 [0, 99]范围内。
进阶:
- 如果矩阵存储在磁盘上,并且磁盘内存是有限的,因此一次最多只能将一行矩阵加载到内存中,该怎么办?
- 如果矩阵太大以至于只能一次将部分行加载到内存中,该怎么办?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/toeplitz-matrix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2.题解
2.1对角线检测
通过Map存储对角线的第一个值,然后判断对角线上其余值。
public class Solution766 {
@Test
public void test766() {
int[][] matrix = {
{1, 2, 3, 4},
{5, 1, 2, 3},
{9, 5, 1, 2}
};
assertTrue(isToeplitzMatrix(matrix));
}
public boolean isToeplitzMatrix(int[][] matrix) {
int m = matrix.length, n = matrix[0].length;
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (!map.containsKey(i - j)) {
map.put(i - j, matrix[i][j]);
} else if (matrix[i][j] != map.get(i - j)) {
return false;
}
}
}
return true;
}
}
- 时间复杂度:
- 空间复杂度:
2.2左上角检测
当前元素同其左上角元素在同一对角线上,故每个元素当有左上角元素时,检测是否相等。
public class Solution766 {
@Test
public void test766() {
int[][] matrix = {
{1, 2, 3, 4},
{5, 1, 2, 3},
{9, 5, 1, 2}
};
assertTrue(isToeplitzMatrix(matrix));
}
public boolean isToeplitzMatrix(int[][] matrix) {
int m = matrix.length, n = matrix[0].length;
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
if (matrix[i][j] != matrix[i - 1][j - 1]) {
return false;
}
}
}
return true;
}
}
- 时间复杂度:
- 空间复杂度: