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.
classSolution:defdiagonalSum(self, mat: List[List[int]])->int:
n =len(mat)
result =0for i inrange(len(mat)):
result += mat[i][i]for i inrange(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.