试题
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Note:
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
Example 1:
Given input matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],
rotate the input matrix in-place such that it becomes:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
Example 2:
Given input matrix =
[
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
],
rotate the input matrix in-place such that it becomes:
[
[15,13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7,10,11]
]
代码
由于只能在原数组上操作,显然要采取交换的措施。对于这种旋转问题,一般采用沿某条线进行翻转。以下为例:
原数组:
[[1,2,3],
[4,5,6],
[7,8,9]]
首先进行上下翻转:只需要按每行进行数值的交换。
[[3,2,1],
[6,5,4],
[9,8,7]]
然后观察上下翻转值,会发现,我们要沿着右对角线进行翻转。这里边有两个注意点:一是由于沿着右对角线进行翻转,我们可以很容易发现是将矩阵的上三角和下三角对应位置进行交换,这样我们就可以很容易确定i和j的取值范围;二是在确定与matrix[i][j]元素的交换元素时,我们要有以下发现:那就是matrix[i][j]距离列尾的距离刚好是交换元素的行位置,matrix[i][j]距离行尾的距离刚好是交换元素的列位置。也就是两个交换元素距离右对角线的两端点的距离具有一个相等的关系。
[[7,4,1],
[8,5,2],
[9,6,3]]
另外还可以尝试先左右翻转的方法。
class Solution {
public void rotate(int[][] matrix) {
int row = matrix.length, col = matrix[0].length;
for(int i=0; i<row; i++){
for(int j=0; j<col/2; j++){
int tmp = matrix[i][j];
matrix[i][j] = matrix[i][col-1-j];
matrix[i][col-1-j] = tmp;
}
}
for(int i=0; i<row; i++){
for(int j=0; j<col-i; j++){
int tmp = matrix[i][j];
matrix[i][j] = matrix[col-1-j][row-1-i];
matrix[col-1-j][row-1-i] = tmp;
}
}
}
}