Leetcode 48 旋转图像(Rotate Image) 题解分析
题目介绍
You are given an n x n 2D matrix
representing an image, rotate the image by 90 degrees (clockwise).
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.
如图,这道题以前做过,其实一看有点蒙,好像规则很容易描述,但是代码很难写,因为要类似于贪吃蛇那样,后来想着应该会有一些特殊的技巧,比如翻转等
代码
直接上码1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37public void rotate(int[][] matrix) {
// 这里真的傻了,长宽应该是一致的,所以取一次就够了
int lengthX = matrix[0].length;
int lengthY = matrix.length;
int temp;
System.out.println(lengthY - (lengthY % 2) / 2);
// 这里除错了,应该是减掉余数再除 2
// for (int i = 0; i < lengthY - (lengthY % 2) / 2; i++) {
/**
* 1 2 3 7 8 9
* 4 5 6 => 4 5 6 先沿着 4 5 6 上下交换
* 7 8 9 1 2 3
*/
for (int i = 0; i < (lengthY - (lengthY % 2)) / 2; i++) {
for (int j = 0; j < lengthX; j++) {
temp = matrix[i][j];
matrix[i][j] = matrix[lengthY-i-1][j];
matrix[lengthY-i-1][j] = temp;
}
}
/**
* 7 8 9 7 4 1
* 4 5 6 => 8 5 2 这里再沿着 7 5 3 这条对角线交换
* 1 2 3 9 6 3
*/
for (int i = 0; i < lengthX; i++) {
for (int j = 0; j <= i; j++) {
if (i == j) {
continue;
}
temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
}
还没到可以直接归纳题目类型的水平,主要是几年前做过,可能有那么点模糊的记忆,当然应该也有直接转的方法