题目描述
旋转图像
给定一个 n × n 的二维矩阵 matrix 表示一个图像。请你将图像顺时针旋转 90 度。
你必须在 原地 旋转图像,这意味着你需要直接修改输入的二维矩阵。请不要 使用另一个矩阵来旋转图像。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[[7,4,1],[8,5,2],[9,6,3]]
示例 2:
输入:matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
输出:[[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]
代码
class Solution {
public void rotate(int[][] matrix) {
int rowNum = matrix.length;
for (int i = 0; i < rowNum / 2; i++){
int[] temp = matrix[i];
matrix[i] = matrix[rowNum - 1 - i];
matrix[rowNum - 1 - i] = temp;
}
for (int i = 0; i < rowNum; i++){
for (int j = i + 1; j < matrix[i].length; j++){
int tmp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = tmp;
}
}
}
}
暴力法
创建个数组
然后计算 移动后下标
先看4个角
先看 5
坐标 0,0 交换后,这个地方应该是 15 来自于 坐标3,0
坐标3,0 交换后,这个地方应该是 16 来自于 坐标3,3
坐标3,3 交换后,这个地方应该是11,来自坐标0,3
外边 除了顶点
暴力解法代码
class Solution {
public void rotate(int[][] matrix) {
int l = 0;
int r = matrix.length - 1;
while ( l < r){
for (int i = 0; i < r - l; i++){
int top = l;
int botttom = r;
// save the top left value
int topleft = matrix[top][l + i];
// move the bottom left to the top left
matrix[top][l + i] = matrix[botttom - i][l];
// move the bottom right to the bottom left
matrix[botttom - i][l] = matrix[botttom][r - i];
// move the top left to the bottom right
matrix[botttom][r - i] = matrix[top + i][r];
// move the top left to the top right
matrix[top + i][r] = topleft;
}
l += 1;
r -= 1;
}
}
}
内圈
Rference
https://leetcode.cn/leetbook/read/top-interview-questions-easy/xnhhkv/