码迷,mamicode.com
首页 > 编程语言 > 详细

【数组】面试题 01.07. 旋转矩阵

时间:2020-05-05 20:09:54      阅读:66      评论:0      收藏:0      [点我收藏+]

标签:tar   cto   star   img   rev   height   旋转   思路   matrix   

题目:

技术图片

 

 

解答:

方法一:会超时间

 1 class Solution {
 2 public:
 3     void rotate(vector<vector<int>>& matrix) 
 4     {
 5         // 思路是: 转置 + 反转每一行
 6 
 7         int len = matrix.size();
 8 
 9         // transpose matrix
10         for (int i = 0; i < len; i++)
11         {
12             for (int j = i; j < len; j++)
13             {
14                 std::swap(matrix[i][j], matrix[j][i]);
15             }
16         }
17 
18         // reverse each row
19         for (int i = 0; i < len; 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(vector<vector<int>>& matrix) 
 4     {
 5         int temp=-1;
 6 
 7         for (int start = 0, end = matrix[0].size() - 1; start < end; start++, end--)
 8         {
 9             for(int s = start, e = end; s < end; s++,e--)
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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!