文章作者:Tyan 博客:noahsnail.com | CSDN | 简书
1. Description
2. Solution
**解析:**Version 1,简单根据主对角线和次对角线的位置规律,把对应位置的数加起来即可,如果是奇数行,要考虑中心元素被加了两次,因此要减掉重复相加。
- Version 1
class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
n = len(mat)
result = 0
for i in range(n):
result = mat[i][i]
result = mat[n-i-1][i]
if n % 2 == 1:
mid = n // 2
result -= mat[mid][mid]
return result
Reference
- https://leetcode.com/problems/matrix-diagonal-sum/