LeetCode 题解工作台
矩阵对角线元素的和
给你一个正方形矩阵 mat ,请你返回矩阵对角线元素的和。 请你返回在矩阵主对角线上的元素和副对角线上且不在主对角线上元素的和。 示例 1: 输入: mat = [[ 1 ,2, 3 ], [4, 5 ,6], [ 7 ,8, 9 ]] 输出: 25 解释: 对角线的和为:1 + 5 + 9 + 3…
2
题型
7
代码语言
3
相关题
当前训练重点
简单 · 数组·matrix
答案摘要
我们可以遍历矩阵的每一行 ,对于每一行,我们可以计算出两个对角线上的元素,即 和 $\textit{row}[i][n - i - 1]$,其中 是矩阵的行数。如果 $i = n - i - 1$,则说明当前行的对角线上只有一个元素,否则有两个元素。我们将其加到答案中即可。 遍历完所有行后,即可得到答案。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·matrix 题型思路
题目描述
给你一个正方形矩阵 mat,请你返回矩阵对角线元素的和。
请你返回在矩阵主对角线上的元素和副对角线上且不在主对角线上元素的和。
示例 1:

输入:mat = [[1,2,3], [4,5,6], [7,8,9]] 输出:25 解释:对角线的和为:1 + 5 + 9 + 3 + 7 = 25 请注意,元素 mat[1][1] = 5 只会被计算一次。
示例 2:
输入:mat = [[1,1,1,1], [1,1,1,1], [1,1,1,1], [1,1,1,1]] 输出:8
示例 3:
输入:mat = [[5]] 输出:5
提示:
n == mat.length == mat[i].length1 <= n <= 1001 <= mat[i][j] <= 100
解题思路
方法一:逐行遍历
我们可以遍历矩阵的每一行 ,对于每一行,我们可以计算出两个对角线上的元素,即 和 ,其中 是矩阵的行数。如果 ,则说明当前行的对角线上只有一个元素,否则有两个元素。我们将其加到答案中即可。 遍历完所有行后,即可得到答案。
时间复杂度 ,其中 是矩阵的行数。空间复杂度 。
class Solution:
def diagonalSum(self, mat: List[List[int]]) -> int:
ans = 0
n = len(mat)
for i, row in enumerate(mat):
j = n - i - 1
ans += row[i] + (0 if j == i else row[j])
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) because a single loop iterates over n elements. Space complexity is O(1) since only one sum variable is maintained and no extra structures are used. |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Look for an optimized single-pass solution rather than two separate loops.
- question_mark
Check if the candidate handles the overlap of diagonals correctly in odd-length matrices.
- question_mark
Verify understanding of Array plus Matrix access patterns and index calculations.
常见陷阱
外企场景- error
Double-counting the central element when n is odd.
- error
Iterating over extra loops unnecessarily instead of combining diagonal sums in one pass.
- error
Miscalculating secondary diagonal indices, especially off-by-one errors.
进阶变体
外企场景- arrow_right_alt
Calculate diagonal sums for rectangular matrices, summing only valid diagonal elements.
- arrow_right_alt
Return the sum of diagonals excluding elements greater than a threshold value.
- arrow_right_alt
Compute the difference between primary and secondary diagonal sums for analysis.