1572. Matrix Diagonal Sum

1572. Matrix Diagonal Sum

Question

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.

Solution

双指针记录两个矩阵对应的位置,遍历相加即可。

注意当两个指针指向同一个位置时需要跳过一个和。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public int diagonalSum(int[][] mat) {
int limit = mat.length;
int sum = 0;
int i = 0, j = mat.length-1;
while(i < mat.length){

if(i != j){
sum += mat[i][i];
sum += mat[i][j];
}
else{
sum += mat[i][i];
}
i++;
j--;
}
return sum;
}
}
Author

Xander

Posted on

2023-05-08

Updated on

2023-05-08

Licensed under

Comments