LeetCode Brush Questions 1572. Sum of Diagonal Elements of Matrix

LeetCode Brush Questions 1572. Sum of Diagonal Elements of Matrix

I don't know where I am going, but I am already on my way!
Time is hurried, although I have never met, but I met Yusi, it is really a great fate, thank you for your visit!
  • Topic :
    Give you a square matrix mat, please return the sum of the diagonal elements of the matrix.
    Please return the sum of the elements on the main diagonal of the matrix and the elements on the sub-diagonal and not on the main diagonal.
  • Example :
    Insert picture description here
示例 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
  • Tips :
    • n == mat.length == mat[i].length
    • 1 <= n <= 100
    • 1 <= mat[i][j] <= 100
  • Code 1:
class Solution:
    def diagonalSum(self, mat: List[List[int]]) -> int:
        n = len(mat)
        result = 0
        for i in range(len(mat)):
            result += mat[i][i]
        for i in range(n):
            if i == n-1-i:
                continue
            result += mat[i][n-1-i]
        return result
# 执行用时:44 ms, 在所有 Python3 提交中击败了64.00%的用户
# 内存消耗:13.4 MB, 在所有 Python3 提交中击败了81.71%的用户
  • Algorithm description:
    Find the size of the matrix, add the sum of the elements of the main diagonal, and the two subscripts of the elements of the main diagonal are equal; then add the sum of the elements of the sub-diagonal to determine whether the element subscripts are equal If they are equal, it means that it is the element of the main diagonal, skip, continue to accumulate, and return the result.

Guess you like

Origin blog.csdn.net/qq_34331113/article/details/108859251