avatar

LeetCode-1419 旋转矩阵

📝题目

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
给定一幅由 N × N 矩阵表示的图像,其中每个像素的大小为 4 字节。请你设计一种算法,将图像旋转 90 度。(不占用额外空间能否做到?)

示例 1:

给定 matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],

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

示例 2:

给定 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]
]


📝思路

想法一:按照数学规律直接改变相应位置的值,需要额外拷贝一个副本作为数据来源。
想法二:不占用额外空间, 先将矩阵以对角线为轴翻转再左右对称翻转。
🐣:不考虑性能的话简直就一水题,强制缩减时空复杂度的话,倒真不容易想到这个翻转法…

📝题解

1
2
3
4
5
6
7
8
9
10
11
//想法一

void rotate(vector<vector<int>>& matrix) {
vector<vector<int>> c_matrix = matrix;
int len = matrix.size();
for (int i = 0; i < len; ++i){
for (int j = 0; j < len; ++j){
matrix[i][j] = c_matrix[len-1-j][i];
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//想法二

void rotate(vector<vector<int>>& matrix) {
int len = matrix.size();

//以对角线为轴翻转
for (int i = 0; i < len-1; ++i){
for (int j = i+1; j < len; ++j){
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}

//左右对称翻转
for (int j = 0; j < len/2; ++j){
for (int i = 0; i < len; ++i){
int temp = matrix[i][j];
matrix[i][j] = matrix[i][len-1-j];
matrix[i][len-1-j] = temp;
}
}
}
Author:WhiteBeerHouse
Link:https://github.com/WhiteBeerHouse/WhiteBeerHouse.github.io/tree/master/2020/04/11/LeetCode-1419-%E6%97%8B%E8%BD%AC%E7%9F%A9%E9%98%B5/
Copyright Notice:All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.