Subject address:
https://leetcode.com/problems/matrix-diagonal-sum/
Given a nnn- order square matrix, find all its lengthnnThe sum of the elements on the diagonal of n . Do not count the elements in the same position twice.
code show as below:
public class Solution {
public int diagonalSum(int[][] mat) {
int res = 0, n = mat.length;
for (int i = 0; i < n; i++) {
res += mat[i][i] + mat[i][n - 1 - i];
// 把重复的数减掉
if (i == n - 1 - i) {
res -= mat[i][i];
}
}
return res;
}
}
Time complexity O (n) O(n)O ( n ) , spaceO (1) O (1)O ( 1 )。