leetcode 1572. Matrix Diagonal Sum

insert image description here

Find the sum of the elements on the main diagonal and the second diagonal of the matrix, and the same element will not be added repeatedly.

Ideas:

You can add mat[ i ][ i ]. But taking two-dimensional array elements is less efficient than taking one-dimensional array elements.
So take elements from both ends to the middle by row (one-dimensional array). That is mat[ i ] and mat[ n - 1 - i ].

public int diagonalSum(int[][] mat) {
    
    
    int n = mat.length;
    if(n == 1) return mat[0][0];
    int sum = 0;
    int i = 0;

    for(int[] row : mat) {
    
    
        if(n-1-i == i) sum += row[i];
        else sum = sum + row[i] + row[n-1-i];
        i ++;
    }
    return sum;
}

Guess you like

Origin blog.csdn.net/level_code/article/details/130552456