Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 9a21b42

Browse files
committed
Create 1572-MatrixDiagonalSum.py
1 parent 86530b9 commit 9a21b42

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

‎src/1572-MatrixDiagonalSum.py‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
#!/usr/bin/env python3
2+
"""
3+
CREATED AT: 2022年11月12日
4+
5+
URL: https://leetcode.com/problems/matrix-diagonal-sum/
6+
7+
GITHUB: https://github.com/Jiezhi/myleetcode
8+
9+
FileName: 1572-MatrixDiagonalSum
10+
11+
Difficulty: Easy
12+
13+
Desc:
14+
15+
Tag:
16+
17+
See:
18+
19+
"""
20+
from tool import *
21+
22+
23+
class Solution:
24+
def diagonalSum(self, mat: List[List[int]]) -> int:
25+
"""
26+
Runtime: 222 ms, faster than 64.61%
27+
Memory Usage: 14.1 MB, less than 55.99%
28+
n == mat.length == mat[i].length
29+
1 <= n <= 100
30+
1 <= mat[i][j] <= 100
31+
"""
32+
n = len(mat)
33+
ret = sum(mat[i][i] + mat[i][-i - 1] for i in range(n))
34+
return ret - mat[n // 2][n // 2] if n & 1 else ret
35+
36+
37+
def test():
38+
assert Solution().diagonalSum(mat=[[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == 25
39+
assert Solution().diagonalSum(mat=[[5]]) == 5
40+
41+
42+
if __name__ == '__main__':
43+
test()

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /