【数组】面试题 01.07. 旋转矩阵
标签:tar cto star img rev height 旋转 思路 matrix
题目:
解答:
方法一:会超时间
1 class Solution {
2 public:
3 void rotate(vectorint>>& matrix)
4 {
5 // 思路是: 转置 + 反转每一行
6
7 int len = matrix.size();
8
9 // transpose matrix
10 for (int i = 0; i )
11 {
12 for (int j = i; j )
13 {
14 std::swap(matrix[i][j], matrix[j][i]);
15 }
16 }
17
18 // reverse each row
19 for (int i = 0; i )
20 {
21 int beg = 0;
22 int end = len - 1;
23 while (beg end)
24 {
25 std::swap(matrix[i][beg], matrix[i][end]);
26 }
27 }
28
29 }
30 };
方法二:
1 class Solution {
2 public:
3 void rotate(vectorint>>& matrix)
4 {
5 int temp=-1;
6
7 for (int start = 0, end = matrix[0].size() - 1; start )
8 {
9 for(int s = start, e = end; s )
10 {
11 temp=matrix[start][s];
12 matrix[start][s]=matrix[e][start];
13 matrix[e][start]=matrix[end][e];
14 matrix[end][e]=matrix[s][end];
15 matrix[s][end]=temp;
16 };
17 };
18 }
19 };
【数组】面试题 01.07. 旋转矩阵
标签:tar cto star img rev height 旋转 思路 matrix
原文地址:https://www.cnblogs.com/ocpc/p/12831840.html
评论