LeetCode 题解工作台

矩阵对角线元素的和

给你一个正方形矩阵 mat ,请你返回矩阵对角线元素的和。 请你返回在矩阵主对角线上的元素和副对角线上且不在主对角线上元素的和。 示例 1: 输入: mat = [[ 1 ,2, 3 ], [4, 5 ,6], [ 7 ,8, 9 ]] 输出: 25 解释: 对角线的和为:1 + 5 + 9 + 3…

category

2

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·matrix

bolt

答案摘要

我们可以遍历矩阵的每一行 ,对于每一行,我们可以计算出两个对角线上的元素,即 和 $\textit{row}[i][n - i - 1]$,其中 是矩阵的行数。如果 $i = n - i - 1$,则说明当前行的对角线上只有一个元素,否则有两个元素。我们将其加到答案中即可。 遍历完所有行后,即可得到答案。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·matrix 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个正方形矩阵 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].length
  • 1 <= n <= 100
  • 1 <= mat[i][j] <= 100
lightbulb

解题思路

方法一:逐行遍历

我们可以遍历矩阵的每一行 row[i]\textit{row}[i],对于每一行,我们可以计算出两个对角线上的元素,即 row[i][i]\textit{row}[i][i]row[i][ni1]\textit{row}[i][n - i - 1],其中 nn 是矩阵的行数。如果 i=ni1i = n - i - 1,则说明当前行的对角线上只有一个元素,否则有两个元素。我们将其加到答案中即可。 遍历完所有行后,即可得到答案。

时间复杂度 O(n)O(n),其中 nn 是矩阵的行数。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
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
speed

复杂度分析

指标
时间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)
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

矩阵对角线元素的和题解:数组·matrix | LeetCode #1572 简单