leetcode链接:1572. 矩阵对角线元素的和
此题蛮简单的,可以不看
题目分析



方案一
对角线相加,长度为奇数的时候进行特殊处理。
1 2 3 4 5 6 7 8 9 10 11 12
| class Solution { public int diagonalSum(int[][] mat) { int result = 0, length = mat.length;
for (int i = 0; i < length; i++) { result += mat[i][i] + mat[i][length - 1 - i]; } if (length%2 == 1) result -= mat[length / 2][length / 2]; return result; } }
|
结果
解答成功:
执行耗时:0 ms,击败了100.00% 的Java用户
内存消耗:42.7 MB,击败了47.78% 的Java用户
分析
时间复杂度:
O( n )
空间复杂度:
O( 1 )
官方题解
https://leetcode.cn/problems/matrix-diagonal-sum/solutions/441166/ju-zhen-dui-jiao-xian-yuan-su-de-he-by-leetcode-so/
方法一:遍历矩阵

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| class Solution { public int diagonalSum(int[][] mat) { int n = mat.length, sum = 0; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { if (i == j || i + j == n - 1) { sum += mat[i][j]; } } } return sum; } }
作者:力扣官方题解 链接:https: 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
|

方法二:枚举对角线元素

1 2 3 4 5 6 7 8 9 10 11 12 13 14
| class Solution { public int diagonalSum(int[][] mat) { int n = mat.length, sum = 0, mid = n / 2; for (int i = 0; i < n; ++i) { sum += mat[i][i] + mat[i][n - 1 - i]; } return sum - mat[mid][mid] * (n & 1); } }
作者:力扣官方题解 链接:https: 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
|
