常规解法如下,目前没发现有更好的方法,时间复杂度优于O(N).
class Solution {
public:
int diagonalSum(vector<vector<int>>& mat) {
int n = mat.size(),sum = 0;
for(int i = 0;i < n;i++)
{
sum += mat[i][i] + mat[i][n -1 -i];
}
//sub middle element,when n is odd,it add twice.
if(n & 1)
sum = sum - mat[n/2][n/2];
return sum;
}
};