leetcode之图像旋转(Rotate Image)

1.新建一个数组,将原数组的数据按规律复制到新数组,这种方法做不到in-place,占用了额外一个数组的空间

newx = y;
newy = n-1-x;

2.我们可以按ring by ring的顺序进行操作
交换在每个ring上的4个点之间进行

public class Solution {
    public void rotate(int[][] matrix) {
        int n = matrix.length;
        for(int x = 0; x <= (n - 1) >> 1; x++) {
            for(int y = x; y <= n - 2 - x; y++) {
                int newx1 = y;
                int newy1 = n - 1 - x;
                int newx2 = newy1;
                int newy2 = n - 1 - newx1;
                int newx3 = newy2;
                int newy3 = n - 1 - newx2;
                int temp = matrix[newx1][newy1];

                matrix[newx1][newy1] = matrix[x][y];
                matrix[x][y] = matrix[newx3][newy3];
                matrix[newx3][newy3] = matrix[newx2][newy2];
                matrix[newx2][newy2] = temp;

            }
        }
    }
}

这里写图片描述
3.将上下的行进行反转,然后按主对角线进行对称交换;这这种方法也很容易做到逆时针旋转。

/*
 * clockwise rotate
 * first reverse up to down, then swap the symmetry 
 * 1 2 3     7 8 9     7 4 1
 * 4 5 6  => 4 5 6  => 8 5 2
 * 7 8 9     1 2 3     9 6 3
*/

/*
 * anticlockwise rotate
 * first reverse left to right, then swap the symmetry
 * 1 2 3     3 2 1     3 6 9
 * 4 5 6  => 6 5 4  => 2 5 8
 * 7 8 9     9 8 7     1 4 7
*/

转载于:https://www.cnblogs.com/season-peng/p/6713496.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值