Leetcode 1572. Matrix Diagonal Sum

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Matrix Diagonal Sum

2. Solution

解析:Version 1,简单根据主对角线和次对角线的位置规律,把对应位置的数加起来即可,如果是奇数行,要考虑中心元素被加了两次,因此要减掉重复相加。

  • Version 1
1
2
3
4
5
6
7
8
9
10
11
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

  1. https://leetcode.com/problems/matrix-diagonal-sum/
如果有收获,可以请我喝杯咖啡!