Skip to content

Commit dbf9011

Browse files
authored
Create matrix-diagonal-sum.cpp
1 parent a6e05ef commit dbf9011

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

C++/matrix-diagonal-sum.cpp

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
int diagonalSum(vector<vector<int>>& mat) {
7+
const int n = mat.size();
8+
int result = 0;
9+
for (int i = 0; i < n; ++i) {
10+
result += mat[i][i] + mat[n - 1 - i][i];
11+
}
12+
if (n % 2) {
13+
result -= mat[n / 2][n / 2];
14+
}
15+
return result;
16+
}
17+
};

0 commit comments

Comments
 (0)