๋ฌธ์ ๋งํฌ
Rotate Image - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
์ฃผ์ด์ง 2์ฐจ์ ๋ฐฐ์ด์ ์๊ณ๋ฐฉํฅ์ผ๋ก ํ์ ์์ผ ๋ฐํํ๋ ๋ฌธ์ ์ด๋ค
์ฃผ์์ฌํญ : ์๋ก์ด ๋ฐฐ์ด์ ๋ง๋ค์ง ๋ง๊ณ ๊ธฐ์กด ๋ฐฐ์ด์ ๋ณ๊ฒฝ์ํค๋ ๋ฐฉํฅ์ผ๋ก ์งํํด์ผํ๋ค.
์ ๊ทผ ๋ฐฉ๋ฒ
ํ๊ฐ์ง ๊ท์น์ ๋ฐ๊ฒฌํ์๋ค.
ํ๋ ฌ์ ๋๊ฐ์ ์ ๊ธฐ์ค์ผ๋ก swapํ ๋ค, ๋ชจ๋ ํ์ ๋ค์ง์ผ๋ฉด ์๊ณ๋ฐฉํฅ์ผ๋ก ํ์ ๋ ํ๋ ฌ์ด ๋ฐํ๋๋ค.
=> ๋๊ฐ์ ๊ธฐ์ค์ผ๋ก swap
1 2 3 4 5 6 7 8 9
=> swapํ ํ๋ ฌ์ row๋ฅผ reverse
1 4 7 2 5 8 3 6 9
7 4 1 8 5 2 9 6 3
์ด๋ฌํ ๊ณผ์ ์ ๊ทธ๋๋ก ์ฝ๋๋ก ๋ณํํ๋ฉด ๋๋ค.
1. ๊ธฐ์กด ๋ฐฐ์ด์ ๋๊ฐ์ ๊ธฐ์ค์ผ๋ก swap
for(let i =0;i<row;i++){ for(let j = i;j<col;j++){ [matrix[i][j],matrix[j][i]] = [matrix[j][i],matrix[i][j]] } }โ
2. swapํ ๋ฐฐ์ด์ row๋ฅผ ๊ธฐ์ค์ผ๋ก reverse()for(i=0;i<row;i++){ matrix[i].reverse(); }
/**
* @param {number[][]} matrix
* @return {void} Do not return anything, modify matrix in-place instead.
*/
var rotate = function(matrix) {
let row = matrix.length;
let col = matrix[0].length;
for(let i =0;i<row;i++){
for(let j = i;j<col;j++){
[matrix[i][j],matrix[j][i]] = [matrix[j][i],matrix[i][j]]
}
}
for(i=0;i<row;i++){
matrix[i].reverse();
}
return matrix;
};
'์ฝ๋ฉํ ์คํธ > LeetCode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[LeetCode] Numbers With Same Consecutive Differences (0) | 2022.09.03 |
---|---|
[LeetCode] Reduce Array Size to The Half (0) | 2022.08.18 |
[LeetCode] Unique Morse Code Words (0) | 2022.08.17 |
[LeetCode] Combination Sum IV (0) | 2022.08.05 |
[LeetCode] My Calendar I (0) | 2022.08.03 |