题目:
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?
从最外层到最里层,依次将对应位置元素进行交换。
时间复杂度:O(n^2)
空间复杂度:0
实现:
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
int n = matrix.size();
int a = 0;
int b = n-1;
while(a<b){
for(int i=0;i<(b-a);++i){
swap(matrix[a][a+i], matrix[a+i][b]);
swap(matrix[a][a+i], matrix[b][b-i]);
swap(matrix[a][a+i], matrix[b-i][a]);
}
++a;
--b;
}
}
};