reoger的记录

--以后的你会感激现在那么努力的自己

0%

旋转图像

48. 旋转图像(Rotate Image)

题目难度: 中等

给定一个 n _× _n 的二维矩阵表示一个图像。

将图像顺时针旋转 90 度。

说明:

你必须在旋转图像,这意味着你需要直接修改输入的二维矩阵。请不要使用另一个矩阵来旋转图像。

示例 1:

1
2
3
4
5
6
7
8
9
10
11
12
13
给定 **matrix** = 
[
[1,2,3],
[4,5,6],
[7,8,9]
],

**原地**旋转输入矩阵,使其变为:
[
[7,4,1],
[8,5,2],
[9,6,3]
]

示例 2:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
给定 **matrix** =
[
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
],

**原地**旋转输入矩阵,使其变为:
[
[15,13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7,10,11]
]

Solution

思路一

先上线交换,再斜角交换。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
例如,原数组
[
[1,2,3],
[4,5,6],
[7,8,9]
],

上下替换后:
[
[7,8,9],
[4,5,6],
[1,2,3]
],
然后再斜角替换:
[
[7,4,1],
[8,5,2],
[9,6,3]
],

实现代码。
Language: Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
   public void rotate(int[][] matrix) {
        int len = matrix.length;
       //上下反转
       for(int i=0;i<len/2;i++){
           for(int j=0;j<len;j++){
              int temp = matrix[i][j];
               matrix[i][j] = matrix[len-i-1][j];
               matrix[len-i-1][j] = temp;
               
          }
      }
       
       //斜角反转
       for(int i=0;i<len;i++){
           for(int j=i+1;j<len;j++){
               int temp = matrix[i][j];
                matrix[i][j] =  matrix[j][i];
               matrix[j][i] =  temp;
          }
      }
  }
}

思路二:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public void rotate(int[][] matrix) {
int N = matrix.length;
int M, row, col, nextRow, nextCol, now, next, offset;
for (int i = 0; i < N / 2; i++) { //圈数
M = (i + 1) * 2 + (N & 1);
for (int j = 0; j < M - 1; j++) { //该圈的长度
offset = N / 2 - i - 1;
row = 0;
col = j;
now = matrix[+offset][col + offset];
for (int k = 0; k < 4; k++) { //换4个
nextRow = col;
nextCol = M - 1 - row;
next = matrix[nextRow + offset][nextCol + offset];
matrix[nextRow + offset][nextCol + offset] = now;
now = next;
row = nextRow;
col = nextCol;
}
}
}
}
}