本题为LeetCode中的第48道题,今天咱们就来看看这道题,再顺便提一下Java中数组的深浅拷贝
这道题是我没做出来,偷懒开辟了其他数组,不过还给过了,就在这贴上吧
给定一个 n × n 的二维矩阵表示一个图像。
将图像顺时针旋转 90 度。
说明:
你必须在原地旋转图像,这意味着你需要直接修改输入的二维矩阵。请不要使用另一个矩阵来旋转图像。
示例 1:
1 | 给定 matrix = |
示例 2:
1 | 给定 matrix = |
大概说一下我的思路,像这种题一般都有规律,我们只需要找出数组下标转移的规律即可解题:
咱们从示例一来分析
1 | [0,0]————>[0,2] |
来看一段侧四代码:
1 | @Test |
这段代码就计算出了后面的坐标
再来看看我的完整代码: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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59/**
* @author RickYinPeng
* @ClassName Rotating_image
* @Description LeetCode中第48道题
* @date 2018/10/10/22:55
*
* 题目名称:旋转图像
*/
public class Rotating_image {
public static void main(String[] args) {
int[][] num = {
{1,2,3},
{4,5,6},
{7,8,9}
};
rotate(num);
for(int i = 0;i<num.length;i++){
for(int j = 0;j<num.length;j++){
System.out.print(num[i][j]+",");
}
System.out.println();
}
}
public static void rotate(int[][] matrix) {
int length = matrix.length;
int i = 0;
int j = length;
int count_j = 0;
int[][] matrixTemp = new int[length][length];
for(int f = 0;f<matrix.length;f++) {
matrixTemp[f] = matrix[f].clone();
}
int a = 0;
for(int x =0;x<matrixTemp.length;x++) {
for(int y = 0;y<matrix.length;y++) {
a = matrixTemp[x][y];
//计算i的值
i = i % 3;
//计算j的值
if (count_j % length == 0) {
j--;
}
System.out.println(a);
System.out.println("["+i+","+j+"]");
matrix[i][j] = a;
i++;
count_j++;
}
}
}
}
这里还了解了Java数组的深浅拷贝,这个后面我会专门写一篇的,这里就不说了