48. Rotate Image - Medium
前往題目
想法
- 快速找了一下規律,沒有找到
思路
- 每個
cell
都反轉其row
和column
,也就是(1, 0)
變為(0, 1)
,兩個cell
互換 - 然後每行前後對調
Time: $O(N^2)$
Space: O(1)
Code
class Solution {
public void rotate(int[][] matrix) {
// Swap rows and columns
for (int row = 0; row < matrix.length; ++row) {
// 注意是col=row,不是從零開始
for (int col = row; col < matrix[0].length; ++col) {
int temp = matrix[row][col];
matrix[row][col] = matrix[col][row];
matrix[col][row] = temp;
}
}
// Swap each line horizontally
for (int row = 0; row < matrix.length; ++row) {
for (int col = 0; col < matrix.length / 2; ++col) {
int temp = matrix[row][col];
matrix[row][col] = matrix[row][matrix.length - 1 - col];
matrix[row][matrix.length - 1 - col] = temp;
}
}
}
}
48. Rotate Image - Medium
https://f88083.github.io/2024/01/10/48-Rotate-Image-Medium/