-
题目
A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same element.
Now given an
M x N
matrix, returnTrue
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.
-
题目大意&解题思路
这道题是给你一个矩阵让你判断该矩阵其对角线上的元素是否都相同。
开始用的是笨方法,直脑筋,就是从最底下的对角线依次判断。结果时间很久。
-
方法一
bool isToeplitzMatrix(vector<vector<int>>& matrix) {
int col = matrix[0].size();
int row = matrix.size();
int i = row - 1; /*确定起始位置*/
int j = 0;
for(int n = 0; n < row+col-1; ++n ){ /*确定对角线数量*/
vector<int> temp_v;
int temp_i = i;
int temp_j = j;
for( ; i < row && j < col; i++, j++ ){ /*将对角线上的元素插入数组中*/
temp_v.push_back(matrix[i][j]);
}
i = temp_i; /*将i和j恢复到循环前*/
j = temp_j;
sort(temp_v.begin(), temp_v.end()); /*排序然后判断其是否相同*/
if( temp_v.front() != temp_v.back() )
return false;
if( i > 0 && j == 0 ) /*确定下一个对角线的起始位置*/
i--;
else if( i == 0 )
j++;
}
return true;
}
-
结果一
-
方法二
其实可以遍历[m*n]矩阵中的[m-1,n-1]行矩阵,每次遍历到一个位置(x,y)判断其与(x+1,y+1)位置元素是否相等,不想等则返回false。
bool isToeplitzMatrix(vector<vector<int>>& matrix) {
int row = matrix.size();
int col = matrix[0].size();
for( int i = 0; i < row - 1; ++i ){ /*遍历row-2 col-2行的矩阵*/
for( int j = 0; j < col - 1; ++j ){
if( matrix[i+1][j+1] != matrix[i][j] )
return false;
}
}
return true;
}
-
实验结果二