题目描述:
You are given an n x n 2D matrix representing an image.
Rotate the image by 90
degrees (clockwise).
Example
题目思路:
Given a matrix
[
[1,2],
[3,4]
]
rotate it by 90 degrees (clockwise), return
[
[3,1],
[4,2]
]
这题重点在找规律:可以发现转了90°之后的matrix,相当于先把matrix元素对角线互换以后,每一行再做reverse。
Mycode(AC = 28ms):
class Solution {
public:
/**
* @param matrix: A list of lists of integers
* @return: Void
*/
void rotate(vector<vector<int> > &matrix) {
// write your code here
int num_rows = matrix.size();
if (num_rows == 0) return;
int num_cols = matrix[0].size();
// swap (i, j) and (j, i)
for (int i = 0; i < num_rows; i++) {
for (int j = i + 1; j < num_cols; j++) {
int tmp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = tmp;
}
}
// reverse each row
for (int i = 0; i < num_rows; i++) {
reverse(matrix[i].begin(), matrix[i].end());
}
}
};