Article directory
One [topic category]
- matrix
Two [question difficulty]
- Simple
Three [topic number]
- 1572. The sum of matrix diagonal elements
Four [title description]
- Given a square matrix mat, please return the sum of the diagonal elements of the matrix.
- Please return the sum of the elements on the main diagonal of the matrix and the elements on the subdiagonal but not on the main diagonal.
Five [topic examples]
-
Example 1:
-
Input: mat = [[1,2,3],
[4,5,6],
[7,8,9]] -
Output: 25
-
Explanation: The sum of the diagonals is: 1 + 5 + 9 + 3 + 7 = 25. Note that the element mat[1][1] = 5 will only be evaluated once.
-
Example 2:
- Input: mat = [[1,1,1,1],
[1,1,1,1],
[1,1,1,1],
[1,1,1,1]] - Output: 8
- Input: mat = [[1,1,1,1],
-
Example 3:
- Input: mat = [[5]]
- Output: 5
Six [topic prompt]
- n = = m a t . l e n g t h = = m a t [ i ] . l e n g t h n == mat.length == mat[i].length n==mat.length==mat[i].length
- 1 < = n < = 100 1 <= n <= 100 1<=n<=100
- 1 < = m a t [ i ] [ j ] < = 100 1 <= mat[i][j] <= 100 1<=mat[i][j]<=100
Seven [problem-solving ideas]
- Define i to traverse the number of rows of the two-dimensional array, and j to traverse the number of columns of the two-dimensional array
- If i==j, it means the element of the main diagonal
- If i+j==n-1, it means that it is an element of the sub-diagonal
- Use
||
to judge, so that the elements of the main diagonal and the sub-diagonal will not be added once more, because the array is only traversed once - Then sum them, and finally return the result
Eight 【Time Frequency】
- Time complexity: O ( n 2 ) O(n^2)O ( n2), n n n is the length of the incoming square array
- Space complexity: O ( 1 ) O(1)O(1)
Nine [code implementation]
- Java language version
class Solution {
public int diagonalSum(int[][] mat) {
int n = mat.length;
int res = 0;
for(int i = 0;i < n;i++){
for(int j = 0;j < n;j++){
if(i == j || i + j == n - 1){
res += mat[i][j];
}
}
}
return res;
}
}
- C language version
int diagonalSum(int** mat, int matSize, int* matColSize)
{
int n = matSize;
int res = 0;
for(int i = 0;i < n;i++)
{
for(int j = 0;j < n;j++)
{
if(i == j || i + j == n - 1)
{
res += mat[i][j];
}
}
}
return res;
}
- Python language version
class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
n = len(mat)
res = 0
for i in range(0,n):
for j in range(0,n):
if i == j or i + j == n - 1:
res += mat[i][j]
return res
- C++ language version
class Solution {
public:
int diagonalSum(vector<vector<int>>& mat) {
int n = mat.size();
int res = 0;
for(int i = 0;i < n;i++){
for(int j = 0;j < n;j++){
if(i == j || i + j == n - 1){
res += mat[i][j];
}
}
}
return res;
}
};
Ten【Submission Results】
-
Java language version
-
C language version
-
Python language version
-
C++ language version