LeetCode48 Rotate Image

时间:2023-03-09 00:29:23
LeetCode48 Rotate Image

题目:

You are given an n x n 2D matrix representing an image.

Rotate the image by 90 degrees (clockwise). (Medium)

Follow up:
Could you do this in-place?

分析:

就是在纸上画一画找到对应关系即可, newMatrix[i][j] = matrix[n - 1 - j][i];

所以简单的方法就是开一个新数组,按照对应关系填入新数组,再拷贝回原来的数组。

代码:

 class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
vector<vector<int>> temp = matrix;
for (int i = ; i < temp.size(); ++i) {
for (int j = ; j < temp[].size(); ++j) {
temp[i][j] = matrix[temp.size() - - j][i];
}
}
for (int i = ; i < matrix.size(); ++i) {
for (int j = ; j < matrix[].size(); ++j) {
matrix[i][j] = temp[i][j];
}
}
return;
}
};

题目中的follow-up,要in-place,考虑原数组上如何处理。

要在原数组上处理局部交换感觉就不好想了(会交换完丢元素),把数组整体一起处理好一些。

再观察对应关系,只需要横纵坐标先颠倒,然后纵坐标上下翻转即可。

代码:

 class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
for (int i = ; i < matrix.size(); ++i) {
for (int j = ; j < i; ++j) {
swap(matrix[i][j], matrix[j][i]);
}
}
for (int j = ; j < matrix.size() / ; ++j) {
for (int i = ; i < matrix[].size(); ++i) {
swap(matrix[i][j], matrix[i][matrix.size() - - j]);
}
}
return;
}
};