|
| 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