Algorithm ๐ง๐ป๐ป/Leetcode
[Leetcode,c++] Rotate Image
dkswnkk
2021. 11. 15. 19:01
๋ฌธ์
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
์ฝ๋
์๋ก์ด ๊ณต๊ฐ ์ ์ธ
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
int n = matrix.size();
vector<vector<int>>ans(n);
for(int i=0; i<n; i++){
for(int k=n-1; k>=0; k--){
ans[i].push_back(matrix[k][i]);
}
}
matrix = ans;
}
};
์ ์๋ฆฌ ํ์
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
int n = matrix.size();
for(int i=0; i<n; i++){
for(int k=0; k<=i; k++){
swap(matrix[i][k],matrix[k][i]);
}
}
for(int i=0; i<n; i++){
reverse(matrix[i].begin(),matrix[i].end());
}
}
};
ํ์ด
ํ๋ ฌ์ ์ค๋ฅธ์ชฝ์ผ๋ก ํ ์นธ ํ์ ํ๋ ๋ฌธ์ ์ ๋๋ค. ๋ฌธ์ ์ "DO NOT allocate another 2D matrix and do the rotation." ์ฆ ๋ค๋ฅธ ๊ณต๊ฐ์ ์ ์ธํ์ง ๋ง๊ณ ํด๊ฒฐํ๋ผ ํ๊ธฐ ๋๋ฌธ์ ์๋ก์ด ๋ฒกํฐ ๊ณต๊ฐ์ ์ ์ธํด์ ์ฝ์ ํ๋ ๋ฐฉ์์ด ์๋ ์ ์๋ฆฌ์์ ํ์ ์ ํด์ ํด๊ฒฐํด์ผ ํฉ๋๋ค.