LeetCode第48题:Rotate Image(Java详解版)

题目:

48.Rotate Image
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.矩阵旋转90度;
2.不允许使用新矩阵,只能在原矩阵上进行操作;

解题思路:

1.矩阵元素交换原理
在这里插入图片描述
2.由于90度旋转,每个数字对应旋转四个位置,例如例1中的 1,7,9,3四个角落数字旋转之后的对应关系为7,9,3,1;
3.设置对应关系,如下:

其中i为行数,j为列数
Height 为高度,Width为宽度
起始位置:matrix[i][j]
逆时针90度位置:
matrix[Height - j - 1][i]
逆时针180度位置:
matrix[Width- i- 1][Height - j- 1]
逆时针270度位置:
matrix[j][Width- i - 1]

4.此题规律: m[i][j] = m[n-1-j][i]

题目代码:

@Test
    public void TestRotateImage(){
        int[][] matrix = {{1,2,3},{4,5,6},{7,8,9}};
        rotate(matrix);
        int[][] test = matrix;
    }

    //[1,2,3]
    //[4,5,6]
    //[7,8,9]
    public void rotate(int[][] matrix) {
        int lenWidth = matrix.length;//3
        if(lenWidth == 0){
            return;
        }
        int lenHeight = matrix[0].length;//3
        int k = lenWidth;//3
        int temp;
        //i = 0 ; j = 0;
        for(int i = 0;i < lenHeight / 2;i++){
            for(int j = i;j < k - 1;j++){
                temp = matrix[i][j];//1
                matrix[i][j] = matrix[lenHeight - j - 1][i];//7
                matrix[lenHeight - j - 1][i] = matrix[lenHeight - i - 1][lenWidth - j -1];//9
                matrix[lenHeight - i -1][lenWidth - j -1] = matrix[j][lenWidth - i -1];//3
                matrix[j][lenWidth - i - 1] = temp;
            }
            k--;
        }
        return;
    }

算法性能:

在这里插入图片描述

总结:
1.此题需要总结出位置元素置换规律;
2.不能新生成矩阵,否则此题就没意义啦;
3.欢迎大家,留言评论,大家一起进步,噢力给!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值