题目---数组操作
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]
]
题目的大意是对数组在原空间 (不能开另一个数组)上进行顺时针90°旋转
解法分两步就可以实现90°旋转(看图自己比划一下):
1. 先对数组进行转置
2. 对数组左右对称交换
代码贴上
class Solution {
public void rotate(int[][] matrix) {
transpose(matrix);
swapLeftRight(matrix);
}
// 矩阵转置函数
public void transpose(int[][] matrix){
for(int i=0;i<matrix.length;i++){
for(int j=0;j<=i;j++){
int tmp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = tmp;
}
}
}
//左右对调函数
public void swapLeftRight(int[][] matrix){
for(int row = 0;row<matrix.length;row++){
int left = 0;
int right = matrix.length-1;
while(left<right){
int tmp = matrix[row][left];
matrix[row][left] = matrix[row][right];
matrix[row][right] = tmp;
left++;
right--;
}
}
}
}