๋ฌธ์
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.
Example 1:
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
Example 3:
Input: mat = [[5]]
Output: 5
Constraints:
- n == mat.length == mat[i].length
- 1 <= n <= 100
- 1 <= mat[i][j] <= 100
์ ๊ทผ๋ฐฉํฅ
row๋ column์ผ๋ก ๋๋์ด์ ๋๊ฐ์ง์ ์๋ฆฌ์๋ฅผ ์ฒดํฌํด์ ํด๋น ์๋ฆฌ์ ์๋ ์๋ฅผ ๋ฝ์์ ๋ฐฐ์ด์ ๋ฃ๊ณ , ๊ทธ ๋ฐฐ์ด์ ํฉ์ฐ์ ๊ตฌํ๋ฉด ๋๊ฒ ๋ค๋ผ๊ณ ์๊ฐํจ. row์ column๋ค์ด ๊ฐ๊ฐ ๊ฐ์์ง ๋ loop๊ฐ ๋๋๋ฉด ๋๊ฒ ๋ค๋ผ๊ณ ์๊ฐํ์. ๊ทธ๋์ while๋ฌธ์ ์ฐ๊ณ ๊ทธ ์์์ ๊ฐ์์ ๋ง๋ ์กฐ๊ฑด๋ฌธ์ ๋ฃ์ loop๋ฅผ ๋ ์. ์ด์ฐ์ด์ฐ ํด๊ฒฐ์ ํ๋๋ฐ ์ค๊ฐ์ column ์์ ์ญํ์ผ๋ก ๋์๊ฐ๋ ์ฝ๋์์ ์์ฒญ ๋ฒ๋ฒ ์.
ํด๊ฒฐ ์ฝ๋
var diagonalSum = function(mat) {
const sum = [];
let startRow = 0;
let endRow = mat.length - 1;
let startCol = 0;
let endCol = mat.length -1;
while(startRow <= endRow && startCol <= endCol){
for(let i = startRow; i<=endRow; i++){
if(startRow === startCol || endRow === endCol){
sum.push(mat[startRow][i])
}
startRow++
}
// row๋ฅผ ํ๋ฒ ์ด๊ธฐํ์์ผ์ค์ผํจ..
startRow = 0
for(let i = endCol; i>=startCol; i--){
// ์ค๊ฐ์ ๊ฒน์ณ์ง๋ row์ column๊ฐ์ ์ ๊ฑฐํ๊ธฐ ์ํด์
if(endCol != startRow && endRow != startCol){
console.log(endCol, endRow,startRow,)
sum.push(mat[i][startRow])
}
endCol--
startRow++
}
const add = sum.reduce((acc, cur) => acc += cur)
console.log(sum, add)
return add
}
};
๋ฐํ์ ๋ฌด์จ์ผ์ด์ผ.. ์ฒ์์ ํด๊ฒฐํด์ ๋ง๋ฅ ์ข์๋๋ฐ ๋ค๋ฅธ ๋ถ๋ค์ด ์ด ์ฝ๋๋ ๋น๊ตํด๋ณด๊ณ ์กฐ๊ธ ์ข์ ํจ..
๋ค๋ฅธ์ฌ๋ ์ฝ๋
var diagonalSum = function(mat) {
const len = mat.length;
let sum = 0;
mat.forEach((row, i) => {
const l = i;
const r = len - i - 1;
sum += l === r ? row[l] : row[l] + row[r];
});
return sum;
};
'๊ฐ๋ฐ > ๐ฌ ์ฝ๋ฉํ ์คํธ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๋น ์ค ํ๊ธฐ๋ฒ Big-O Notation ์ด๋? (2) | 2024.04.25 |
---|---|
[leetCode/Javascript] 2363. Merge Similar Items (0) | 2024.02.27 |
[leetCode/Javascript] 2418. Sort the People (1) | 2024.02.11 |
[LeetCode/Javascript] 216. Combination Sum III (0) | 2024.02.05 |
[leetCode/javascript] 1071. Greatest Common Divisor of Strings (0) | 2024.02.02 |