Java solves the sum problem of matrix diagonal elements
01 Question
Give you 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 sub-diagonal but not on the main diagonal.
Example 1:
输入:mat = [[1,2,3],
[4,5,6],
[7,8,9]]
输出:25
解释:对角线的和为:1 + 5 + 9 + 3 + 7 = 25
请注意,元素 mat[1][1] = 5 只会被计算一次。
Example 2:
输入:mat = [[1,1,1,1],
[1,1,1,1],
[1,1,1,1],
[1,1,1,1]]
输出:8
Example 3:
输入:mat = [[5]]
输出:5
hint:
n == mat.length == mat[i].length
1 <= n <= 100
1 <= mat[i][j] <= 100
02 Knowledge points
- Two-dimensional array
03 My solution
public class shuzu04 {
public static void main(String[] args) {
int[][] mat=new int[][] {
{
1,2,3},
{
4,5,6},
{
7,8,9}};
System.out.println(diagonalSum(mat));
}
public static int diagonalSum(int[][] mat) {
int m=mat[0].length;
int count=0;
for (int i = 0; i < m; i++) {
count+=mat[i][i];
count+=mat[i][m-1-i];
}
if (m%2==1) {
int n=(m-1)/2;
count-=mat[n][n];
}
return count;
}
}