Skip to content

Commit cd59231

Browse files
committed
feat: solve No.1572
1 parent f93b79d commit cd59231

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
# 1572. Matrix Diagonal Sum
2+
3+
- Difficulty: Easy.
4+
- Related Topics: Array, Matrix.
5+
- Similar Questions: Check if Every Row and Column Contains All Numbers, Check if Matrix Is X-Matrix.
6+
7+
## Problem
8+
9+
Given a square matrix `mat`, return the sum of the matrix diagonals.
10+
11+
Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.
12+
13+
 
14+
Example 1:
15+
16+
![](https://assets.leetcode.com/uploads/2020/08/14/sample_1911.png)
17+
18+
```
19+
Input: mat = [[1,2,3],
20+
  [4,5,6],
21+
  [7,8,9]]
22+
Output: 25
23+
Explanation: Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25
24+
Notice that element mat[1][1] = 5 is counted only once.
25+
```
26+
27+
Example 2:
28+
29+
```
30+
Input: mat = [[1,1,1,1],
31+
  [1,1,1,1],
32+
  [1,1,1,1],
33+
  [1,1,1,1]]
34+
Output: 8
35+
```
36+
37+
Example 3:
38+
39+
```
40+
Input: mat = [[5]]
41+
Output: 5
42+
```
43+
44+
 
45+
**Constraints:**
46+
47+
48+
49+
- `n == mat.length == mat[i].length`
50+
51+
- `1 <= n <= 100`
52+
53+
- `1 <= mat[i][j] <= 100`
54+
55+
56+
57+
## Solution
58+
59+
```javascript
60+
/**
61+
* @param {number[][]} mat
62+
* @return {number}
63+
*/
64+
var diagonalSum = function(mat) {
65+
var res = 0;
66+
for (var i = 0; i < mat.length; i++) {
67+
res += mat[i][i] + mat[i][mat.length - 1 - i];
68+
}
69+
if (mat.length % 2) {
70+
var mid = Math.floor(mat.length / 2);
71+
res -= mat[mid][mid];
72+
}
73+
return res;
74+
};
75+
```
76+
77+
**Explain:**
78+
79+
nope.
80+
81+
**Complexity:**
82+
83+
* Time complexity : O(n).
84+
* Space complexity : O(1).

0 commit comments

Comments
 (0)