You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Follow up:
Could you do this in-place?
解法1:新开辟一个矩阵,空间复杂度O(n^2)。
class Solution { public: void rotate(vector<vector<int>>& matrix) { if(matrix.empty() || matrix[0].empty()) return; int n = matrix.size(); vector< vector<int> > tmp(n, vector<int>(n, 0)); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) tmp[j][n - 1 - i] = matrix[i][j]; } for(int i = 0; i < n; i++) copy(tmp[i].begin(), tmp[i].end(), matrix[i].begin()); } };
解法2:矩阵顺时针旋转90°可以通过两个操作来完成:先将矩阵上下翻转,然后将矩阵转置(按左上-右下对角线翻转)。空间复杂度O(1)。
class Solution { public: void rotate(vector<vector<int>>& matrix) { if(matrix.empty() || matrix[0].empty()) return; int n = matrix.size(); for (int i = 0; i < n / 2; i++) { for (int j = 0; j < n; j++) swap(matrix[i][j], matrix[n - 1 - i][j]); } for (int i = 0; i < n; i++) { for (int j = 0; j < i; j++) swap(matrix[i][j], matrix[j][i]); } } };
或者先转置,再左右翻转。reverse能放在第一层for循环内是因为前面进行的转置已经处理好一行了。
class Solution { public: void rotate(vector<vector<int> > &matrix) { if(matrix.empty() || matrix[0].empty()) return; int n = matrix.size(); for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { swap(matrix[i][j], matrix[j][i]); } reverse(matrix[i].begin(), matrix[i].end()); } } };
或者先按右上-左下对角线翻转,再上下翻转。注意按照右上-左下对角线翻转时对应坐标关系。
class Solution { public: void rotate(vector<vector<int>>& matrix) { if(matrix.empty() || matrix[0].empty()) return; int n = matrix.size(); for (int i = 0; i < n; i++) { for (int j = 0; j <n - 1 - i; j++) swap(matrix[i][j], matrix[n - 1 - j][n - 1 - i]); } for (int i = 0; i < n / 2; i++) { for (int j = 0; j < n; j++) swap(matrix[i][j], matrix[n - 1 - i][j]); } } };
或者先左右翻转,再按照右上-左下对角线翻转。
class Solution { public: void rotate(vector<vector<int>>& matrix) { if(matrix.empty() || matrix[0].empty()) return; int n = matrix.size(); for(int i = 0; i < n; i++) reverse(matrix[i].begin(), matrix[i].end()); for (int i = 0; i < n; i++) { for (int j = 0; j < n - 1 - i; j++) swap(matrix[i][j], matrix[n - 1 - j][n - 1 - i]); } } };
解法3:3*3的矩阵可以看做两圈,中间一圈只有一个数字不需要动,只需将外面一圈顺时针旋转90°即可;4*4矩阵两圈,分别顺时针旋转90°即可。因此可以每次旋转一圈,一共需要旋转n/2圈,每圈旋转n-1个数字。
class Solution { public: void rotate(vector<vector<int>>& matrix) { if(matrix.empty() || matrix[0].empty()) return; int n = matrix.size(); for (int i = 0; i < n / 2; i++) //处理矩阵的哪一圈 { for (int j = i; j < n - 1 - i; j++) //每圈需要处理的元素个数 { int tmp = matrix[i][j]; matrix[i][j] = matrix[n - 1 - j][i]; matrix[n - 1 - j][i] = matrix[n - 1 - i][n - 1 - j]; matrix[n - 1 - i][n - 1 - j] = matrix[j][n - 1 - i]; matrix[j][n - 1 - i] = tmp; } } } };
时间: 2024-10-21 08:57:39