矩阵对角线元素的和-输入:mat = [[5]] 输出:5 提示:

时间:2024-02-23 07:08:09
  • n == mat.length == mat[i].length
  • 1 <= n <= 100
  • 1 <= mat[i][j] <= 100
class Solution {
    public int diagonalSum(int[][] mat) {
		int sum = 0;
		for (int i = 0,j = 0,m = mat.length-1; i < mat.length; i++,j++,m--) {
			sum += mat[i][j] + mat[i][m];//计算对角线之和
		}
		if(mat.length % 2 != 0) {//奇数减去中间重复的
			return sum - mat[(mat.length-1)/2][(mat.length-1)/2];
		}else {
			return sum;
		}
    }
}