您的位置:首页 > 其它

leetcode rotate-image(90°旋转矩阵)

2017-05-18 09:12 633 查看
原题:

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

Rotate the image by 90 degrees (clockwise).

Follow up:

Could you do this in-place?

题意就不多说了,比较经典的一个问题,90度顺时针旋转一个n*n的二维矩阵,难点在于只能使用O(1)的空间来存储

思路:举例说明比较清晰

对于一个3*3的矩阵 arr

1 2 3

4 5 6

7 8 9

先用一个临时变量 temp保存左上角的数字 即 temp = 1;然后按如下顺序赋值: 1 = 7, 7 = 9, 9 = 3, 3 = temp,赋值之后矩阵变为

7 2 1

4 5 6

9 8 3

之后temp = 4 按如下顺序赋值: 4 = 8, 8 = 6, 6 = 2, 2 = temp,

矩阵变为

7 4 1

8 5 2

9 6 3

这样外面一层执行了两次完成了赋值

由于内层只有一个数字5,因此结束。

public class Solution {
public void rotate(int[][] matrix) {
int len = matrix.length;
for(int i = 0;i<matrix.length/2;i++)
{
for(int j = i;j<matrix.length-i-1;j++)
{
int temp = matrix[i][j];
matrix[i][j] = matrix[len - j -1][i];
matrix[len - j -1][i] = matrix[len - i - 1][len - j - 1];
matrix[len - i - 1][len - j - 1] = matrix[j][len - i - 1];
matrix[j][len - i - 1] = temp;
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: