标签: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 };
标签:tar cto star img rev height 旋转 思路 matrix
原文地址:https://www.cnblogs.com/ocpc/p/12831840.html