面试题 01.07. 旋转矩阵(Interview question 01.07 Rotation matrix)-其他

面试题 01.07. 旋转矩阵(Interview question 01.07 Rotation matrix)

``````class Solution {
public void rotate(int[][] matrix) {
int m = matrix.length, n = matrix[0].length;

int row1 = 0, col1 = 0, row2 = m - 1, col2 = n - 1;

while (row1 < row2 && col1 < col2) {
for (int i = col1; i < col2; ++i) {
int t = matrix[row1][i];
matrix[row1][i] = matrix[row2 - (i - col1)][col1];
matrix[row2 - (i - col1)][col1] = matrix[row2][col2 - (i - col1)];
matrix[row2][col2 - (i - col1)] = matrix[row1 + (i - col1)][col2];
matrix[row1 + (i - col1)][col2] = t;
}
row1++;
col1++;
row2--;
col2--;
}

}
}
``````
————————

Here’s a picture by n × N matrix represents the image, where the size of each pixel is 4 bytes. Please design an algorithm to rotate the image 90 degrees.

Can you do it without taking up additional memory space?

Source: leetcode

``````class Solution {
public void rotate(int[][] matrix) {
int m = matrix.length, n = matrix[0].length;

int row1 = 0, col1 = 0, row2 = m - 1, col2 = n - 1;

while (row1 < row2 && col1 < col2) {
for (int i = col1; i < col2; ++i) {
int t = matrix[row1][i];
matrix[row1][i] = matrix[row2 - (i - col1)][col1];
matrix[row2 - (i - col1)][col1] = matrix[row2][col2 - (i - col1)];
matrix[row2][col2 - (i - col1)] = matrix[row1 + (i - col1)][col2];
matrix[row1 + (i - col1)][col2] = t;
}
row1++;
col1++;
row2--;
col2--;
}

}
}
``````