1572. 矩陣對角線元素的和
題目描述
給你一個正方形矩陣 mat,請你返回矩陣對角線元素的和。
請你返回在矩陣主對角線上的元素和副對角線上且不在主對角線上元素的和。
示例 1:
輸入:mat = [[1,2,3],
[4,5,6],
[7,8,9]]
輸出:25
解釋:對角線的和為:1 + 5 + 9 + 3 + 7 = 25
請注意,元素 mat[1][1] = 5 只會被計算一次。
示例 2:
輸入:mat = [[1,1,1,1],
[1,1,1,1],
[1,1,1,1],
[1,1,1,1]]
輸出:8
示例 3:
輸入:mat = [[5]]
輸出:5
提示:
n == mat.length == mat[i].length
1 <= n <= 100
1 <= mat[i][j] <= 100文章來源:http://www.zghlxwxcb.cn/news/detail-641863.html
解題思路
思路:主對角線i=j,副對角線i+j=n-1。文章來源地址http://www.zghlxwxcb.cn/news/detail-641863.html
class Solution {
public:
int diagonalSum(vector<vector<int>>& mat) {
int n=mat.size();
int res=0;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(i==j||i+j==n-1)
res+=mat[i][j];
}
}
return res;
}
};
到了這里,關于【每日一題】1572. 矩陣對角線元素的和的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!