【Leetcode】1572. Matrix Diagonal Sum

Subject address:

https://leetcode.com/problems/matrix-diagonal-sum/

Given a nnn- order square matrix, find all its lengthnnThe sum of the elements on the diagonal of n . Do not count the elements in the same position twice.

code show as below:

public class Solution {
    
    
    public int diagonalSum(int[][] mat) {
    
    
        int res = 0, n = mat.length;
        for (int i = 0; i < n; i++) {
    
    
            res += mat[i][i] + mat[i][n - 1 - i];
            // 把重复的数减掉
            if (i == n - 1 - i) {
    
    
                res -= mat[i][i];
            }
        }
        
        return res;
    }
}

Time complexity O (n) O(n)O ( n ) , spaceO (1) O (1)O ( 1 )

Guess you like

Origin blog.csdn.net/qq_46105170/article/details/113068355