LeetCode Solutions
48. Rotate Image
Time: $O(n^2)$ Space: $O(1)$
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
reverse(begin(matrix), end(matrix));
for (int i = 0; i < matrix.size(); ++i)
for (int j = i + 1; j < matrix.size(); ++j)
swap(matrix[i][j], matrix[j][i]);
}
};
class Solution {
public void rotate(int[][] matrix) {
for (int i = 0, j = matrix.length - 1; i < j; ++i, --j) {
int[] temp = matrix[i];
matrix[i] = matrix[j];
matrix[j] = temp;
}
for (int i = 0; i < matrix.length; ++i)
for (int j = i + 1; j < matrix.length; ++j) {
final int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
}
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
matrix.reverse()
for i in range(len(matrix)):
for j in range(i + 1, len(matrix)):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]