文章目录
- Matrix Diagonal Sum 矩阵对角线元素的和
- 问题描述:
- 分析
- 代码
- Tag
Matrix Diagonal Sum 矩阵对角线元素的和
问题描述:
给你一个正方形矩阵 mat
,请你返回矩阵对角线元素的和。
请你返回在矩阵主对角线上的元素和副对角线上且不在主对角线上元素的和。
n = = m a t . l e n g t h = = m a t [ i ] . l e n g t h 1 < = n < = 100 1 < = m a t [ i ] [ j ] < = 100 n == mat.length == mat[i].length\\ 1 <= n <= 100\\ 1 <= mat[i][j] <= 100 n==mat.length==mat[i].length1<=n<=1001<=mat[i][j]<=100
分析
这个问题就是矩阵的对角线遍历。
- 主对角线元素的坐标一定是 a [ i ] [ i ] a[i][i] a[i][i],
- 副对角线的坐标就是 a [ i ] [ j ] , i + j = = n − 1 a[i][j],i+j==n-1 a[i][j],i+j==n−1
其次,要求重合的位置仅计算一次,而只有当n为odd
的情况下,才会重合。
时间复杂度 O ( N ) O(N) O(N),空间复杂度 O ( 1 ) O(1) O(1)
代码
Math
public int diagonalSum(int[][] mat) {int sum = 0,n = mat.length,mid = n/2;if(n==1)return mat[0][0];for(int i = 0;i<n;i++){sum += mat[i][i]+ mat[i][n-1-i]; }return (n&1)==0?sum:sum - mat[mid][mid];}
时间复杂度 O ( N ) O(N) O(N)
空间复杂度 O ( 1 ) O(1) O(1)
Tag
Matrix