Re: [閒聊] 每日LeetCode
1572. Matrix Diagonal Sum
https://leetcode.com/problems/matrix-diagonal-sum/description/
算出所有對角線元素的總和。
Example 1:
https://assets.leetcode.com/uploads/2020/08/14/sample_1911.png

Input: mat = [[1,2,3],
[4,5,6],
[7,8,9]]
Output: 25
Explanation: Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25
Notice that element mat[1][1] = 5 is counted only once.
Example 2:
Input: mat = [[1,1,1,1],
[1,1,1,1],
[1,1,1,1],
[1,1,1,1]]
Output: 8
思路:
1.mat[i][j]對角線上的元素只有兩種情況滿足,i == j 或 i + j = n - 1
遍歷的時候滿足條件就加起來就好。
Java Code:
----------------------------------------
class Solution {
public int diagonalSum(int[][] mat) {
int n = mat.length;
int 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://i.imgur.com/CBMFmWk.jpg

--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 122.100.75.86 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1683563626.A.ECE.html
討論串 (同標題文章)
完整討論串 (本文為第 316 之 719 篇):