标签:style class blog code color 2014
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?
思路:第一种思路是一层一层的进行旋转,比较直观;第二种思路则比较取巧,首先沿着副对角线翻转一次,然后沿着水平中线翻转一次。
代码一:
class Solution {
public:
void rotate(vector<vector<int> > &matrix) {
int n = matrix.size();
for(int i = 0; i < n / 2; i++)
for(int j = i; j < n - i - 1;j++)
{
int temp = 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] = temp;
}
}
};
// LeetCode, Rotate Image
// 思路1,时间复杂度O(n^2),空间复杂度O(1)
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
const int n = matrix.size();
for (int i = 0; i < n; ++i) // 沿着副对角线反转
for (int j = 0; j < n - 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]);
}
};
【Leetcode】Rotate Image,布布扣,bubuko.com
标签:style class blog code color 2014
原文地址:http://blog.csdn.net/lipantechblog/article/details/30474613