LeeCode : 48. Rotate Image 旋转图像90度

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

Rotate the image by 90 degrees (clockwise).

Note:

You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

Example 1:

Given input matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],

rotate the input matrix in-place such that it becomes:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
Example 2:

Given input matrix =
[
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
],

rotate the input matrix in-place such that it becomes:
[
[15,13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7,10,11]
]

代码
由于只能在原数组上操作,显然要采取交换的措施。对于这种旋转问题,一般采用沿某条线进行翻转。以下为例:

原数组:
[[1,2,3],
[4,5,6],
[7,8,9]]

首先进行上下翻转:只需要按每行进行数值的交换。
[[3,2,1],
[6,5,4],
[9,8,7]]

然后观察上下翻转值,会发现,我们要沿着右对角线进行翻转。这里边有两个注意点:一是由于沿着右对角线进行翻转,我们可以很容易发现是将矩阵的上三角和下三角对应位置进行交换,这样我们就可以很容易确定i和j的取值范围;二是在确定与matrix[i][j]元素的交换元素时,我们要有以下发现:那就是matrix[i][j]距离列尾的距离刚好是交换元素的行位置,matrix[i][j]距离行尾的距离刚好是交换元素的列位置。也就是两个交换元素距离右对角线的两端点的距离具有一个相等的关系。
[[7,4,1],
[8,5,2],
[9,6,3]]
另外还可以尝试先左右翻转的方法。

class Solution {
    public void rotate(int[][] matrix) {
        int row = matrix.length, col = matrix[0].length;
        for(int i=0; i<row; i++){
            for(int j=0; j<col/2; j++){
                int tmp = matrix[i][j];
                matrix[i][j] = matrix[i][col-1-j];
                matrix[i][col-1-j] = tmp;
            }
        }
        for(int i=0; i<row; i++){
            for(int j=0; j<col-i; j++){
                int tmp = matrix[i][j];
                matrix[i][j] = matrix[col-1-j][row-1-i];
                matrix[col-1-j][row-1-i] = tmp;
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值