LeetCode 1572. Matrix Diagonal Sum
考点 | 难度 |
---|---|
Matrix | Easy |
题目
Given a square matrix mat
, return the sum of the matrix diagonals.
Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.
思路
先把两条对角线的数加起来,如果matrix的边长是奇数说明有一个重复。
答案
public int diagonalSum(int[][] mat) {
int res = 0;
int n = mat.length;
for (int i=0; i<n; i++) {
res += mat[i][i];
res += mat[n-1-i][i];
}
return n % 2 == 0 ? res : res - mat[n/2][n/2];
}