首页 > 编程语言 > 详细

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

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

题目:

技术分享图片

 

 

解答:

方法一:会超时间

 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. 旋转矩阵

原文:https://www.cnblogs.com/ocpc/p/12831840.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!