LeetCode.48 Rotate Image

本文介绍了一种高效的二维矩阵顺时针旋转90度的算法实现,通过两次对称变换完成旋转,避免了额外内存分配。首先进行垂直翻转,随后沿着逆对角线再次翻转,达到原地旋转的效果。此外还提供了一个更简洁的方法,通过逐层交换元素实现旋转。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

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]
]

提示:该矩阵为对称正方阵,操作只能在原矩阵上进行,不能另外开辟矩阵空间。

分析:(时间复杂度(O(2N^2)))

 

class Solution {
    public void rotate(int[][] matrix) {
        //顺时针旋转90度,在原矩阵的基础上操作,不使用新的矩阵
        //解法:先竖着中间对折一次,之后逆对角线对折一次即可。
        //矩阵为n*n的正方矩阵
        int row=matrix.length;
        int col=row;
        //1.竖中间对折
        //竖中间对折,只需要进行一半即可
        int ax=(col+1)/2;//对称轴
        for(int i=0;i<row;i++){
            for(int j=0;j<ax;j++){
                int temp=matrix[i][j];
                matrix[i][j]=matrix[i][row-1-j];
                matrix[i][row-1-j]=temp;
            }
        }
        
        //2.逆对角线对折
        //只需计算沿逆对角线一半
        for(int i=0;i<row;i++){
            for(int j=row-1-i;j>=0;j--){
               //对称点(row-1-j,j)或者(i,row-1-i)
                int temp=matrix[i][j];
                matrix[i][j]=matrix[i+(row-1-i-j)][row-1-i];
                matrix[i+(row-1-i-j)][row-1-i]=temp;
            }
        }
        
    }
}

推荐算法时间复杂度(O(N^2)):

class Solution {
    public void rotate(int[][] matrix) {
        //顺时针旋转矩阵90度
        //思路:采用上下左右四个点分别交换位置
        //从内向外或者从外向内进行
        if(matrix==null||matrix.length==0) return ;
        int len=matrix.length;
        for(int i=(len-1)/2;i>=0;i--){
            for(int j=i;j<len-i-1;j++){
                //采用从内往外
                //上和右交换
                swap(matrix,i,j,j,len-i-1);
                //下和上交换
                swap(matrix,i,j,len-i-1,len-j-1);
                //左和下交换
                swap(matrix,i,j,len-j-1,i);
            }
            
        }
        
    }
    public void swap(int [][]matrix,int i ,int j,int x,int y){
        int temp=matrix[i][j];
        matrix[i][j]=matrix[x][y];
        matrix[x][y]=temp;
    }
}

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值