Article directory
topic
1572. Sum of Matrix Diagonal Elements
Difficulty: Easy
describe:
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.
Returns the merged binary tree.
Note: The merging process must start from the root node of both trees.
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
Example 3:
Input: mat = [[5]]
Output: 5
hint:
- -n == mat.length == mat[i].length
- 1 <= n <= 100
- 1 <= mat[i][j] <= 100
train of thought
Time complexity analysis : According to the analysis of the range of m and n, two layers of for loop can be used to solve the problem. The time complexity is O(n^2)
. The complexity can be reduced to O(n)
space complexity: O(1)
solution idea : use a layer of for loop to find the sum of the diagonals, and at the same time, according to the parity of the order, if it is odd, you need to subtract the intermediate value once, Even numbers don't
the code
class Solution {
public int diagonalSum(int[][] mat) {
int m = mat.length;
int n = mat[0].length;
int sum =0;
for(int i = 0;i<m;i++){
sum += mat[i][i];
}
for(int j =0;j<n;j++){
sum += mat[j][n-j-1];
if(n % 2 == 1){
sum -= mat[n/2][m/2];
}
return sum;
}
}