https://leetcode.com/problems/toeplitz-matrix/
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:
In the above grid, the diagonals are:
"[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]".
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]
.
Follow up:
- What if the matrix is stored on disk, and the memory is limited such that you can only load at most one row of the matrix into the memory at once?
- What if the matrix is so large that you can only load up a partial row into the memory at once?
算法思路:
方法1:主对角线比较
class Solution {
public:
bool isToeplitzMatrix(vector<vector<int>>& matrix) {
int m = matrix.size();
int n = matrix[0].size();
for (int j = 0; j < n - 1; j++) {
int top_left = matrix[0][j];
int col = j;
for (int i = 1; i < m; i++) {
if (++col >= n) break;
if (matrix[i][col] != top_left) return false;
}
}
for (int i = 1; i < m - 1; i++) {
int top_left = matrix[i][0];
int col = 0;
for (int row = i + 1; row < m; row++) {
if (++col >= n) break;
if (matrix[row][col] != top_left) return false;
}
}
return true;
}
};
方法2:异或
对于follow up可以采用异或操作,具体就是算出第一行的[0...n - 2]异或值,然后与第二行的[1...n - 1]异或值去异或一下看是否为0,不为0,那么直接返回false,是0的话,第二行重复第一行操作,依次类推...
// rows and columns in range [1, 20]
class Solution {
public:
bool isToeplitzMatrix(vector<vector<int>>& matrix) {
int m = matrix.size();
int n = matrix[0].size();
int firstRowCompXor = 0;
for (int j = 0; j < n - 1; j++) firstRowCompXor ^= matrix[0][j];
int secondRowCompXor = 0;
for (int i = 1; i < m; i++) {
int curRowXor = 0;
for (int j = 0; j < n; j++) curRowXor ^= matrix[i][j];
secondRowCompXor = (curRowXor ^ matrix[i][0]);
if ((firstRowCompXor ^ secondRowCompXor) != 0) return false;
firstRowCompXor = (curRowXor ^ matrix[i][n - 1]);
}
return true;
}
};