顺时针旋转矩阵

有一个NxN整数矩阵,请编写一个算法,将矩阵顺时针旋转90度。

给定一个NxN的矩阵,和矩阵的阶数N,请返回旋转后的NxN矩阵。

数据范围:0 < n < 3000<n<300,矩阵中的值满足 0 \le val \le 10000≤val≤1000

要求:空间复杂度O(n^2),时间复杂度 O(n^2)
进阶:空间复杂度 O(1),时间复杂度 O(n^2)
输入:
[[1,2,3],[4,5,6],[7,8,9]],3
返回值:
[[7,4,1],[8,5,2],[9,6,3]]

找规律题,很简单:

import java.util.*;

public class Solution {
    public int[][] rotateMatrix1(int[][] mat, int n) {
        // write code here
        int[][] temp = new int[n][n];//新建temp对象,作为最终返回的对象
        for(int i = 0;i < n;i++){
            for(int j = 0;j < n;j++){
                temp[j][n-1-i] = mat[i][j];//直接交换
            }
        }
        return temp;
    }
    
    public int[][] rotateMatrix(int[][] mat, int n) {
        // write code here
       //由外而内,一层一层地进行变换
        int rotateTimes=n/2;
        int i=0,low=0,high=n-1;
        while(i++<rotateTimes){
            for(int j=0;j<high-low;j++){
                int tmp=mat[low][low+j];
                mat[low][low+j]=mat[high-j][low];
                mat[high-j][low]=mat[high][high-j];
                mat[high][high-j]=mat[low+j][high];
                mat[low+j][high]=tmp;
            }           
            low+=1;
            high-=1;
        }
        return mat;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值