这是破解编码面试中的一个问题。解决方案是,程序先旋转外部边,然后旋转内部边。但是,我在理解这两个for循环的逻辑时遇到了问题。
谁能解释一下代码的逻辑(例如,为什么要做"layer < n/2“,以及"left -> top”和"bottom -> left“的四个步骤,等等)?顺便说一句,当一个人在编码面试中想出这个问题时,他的思维过程会是怎样的?
给定一个由NxN矩阵表示的图像,其中图像中的每个像素都是4个字节,编写一个方法将图像旋转90度。你能就地做这件事吗?
public static void rotate(int[][] matrix, int n) {
for (int layer = 0; layer < n / 2; ++layer) {
int first = layer;
int last = n - 1 - layer;
for(int i = first; i < last; ++i) {
int offset = i - first;
int top = matrix[first][i]; // save top
// left -> top
matrix[first][i] = matrix[last-offset][first];
// bottom -> left
matrix[last-offset][first] = matrix[last][last - offset];
// right -> bottom
matrix[last][last - offset] = matrix[i][last];
// top -> right
matrix[i][last] = top; // right <- saved top
}
}
}
https://stackoverflow.com/questions/25882480
复制相似问题