leetcode 1572. Matrix Diagonal Sum(python)

410 阅读1分钟

描述

Given a square matrix mat, return the sum of the matrix diagonals.

Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.

Example 1:

Input: mat = [[1,2,3],
              [4,5,6],
              [7,8,9]]
Output: 25
Explanation: Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25
Notice that element mat[1][1] = 5 is counted only once.	

Example 2:

Input: mat = [[1,1,1,1],
              [1,1,1,1],
              [1,1,1,1],
              [1,1,1,1]]
Output: 8

Example 3:

Input: mat = [[5]]
Output: 5

Note:

n == mat.length == mat[i].length
1 <= n <= 100
1 <= mat[i][j] <= 100

解析

根据题意就是计算矩阵对角线上元素的和,这样就会发现有一个规律,每行所用到的属于对角线上的元素最多有两个(mat[i][i] 和 mat[i][n-i-1]),最少有一个(mat[i][i]),根据这个规律找出对角线上元素相加即可。

解答

 class Solution(object):
    def diagonalSum(self, mat):
        """
        :type mat: List[List[int]]
        :rtype: int
        """
        n = len(mat)
        s = 0
        for i in range(n):
            s += mat[i][i]
            if i != n - i - 1:
                s += mat[i][n-i-1]
        return s
                   	      
		

运行结果

Runtime: 80 ms, faster than 92.81% of Python online submissions for Matrix Diagonal Sum.
Memory Usage: 13.6 MB, less than 75.91% of Python online submissions for Matrix Diagonal Sum.

原题链接:leetcode.com/problems/ma…

您的支持是我最大的动力