程序员面试金典--题目解析-1.6 左旋右旋N阶矩阵

1.6 题目:

给定一个N*N阶的矩阵,左或右旋转90度,不要使用额外的空间。


解法:

最优的复杂度为O(N^2)

左旋代码:

  1. public static void rotateRight(int[][] matrix,int n){  
  2.         for(int layer = 0;layer< n/2;layer++){  
  3.             int first = layer;  
  4.             int last = n-1-layer;  
  5.             for(int i=first;i<last;i++){  
  6.                 int offset = i-first;  
  7.                 int top = matrix[first][i];  
  8.                 matrix[first][i] = matrix[last-offset][first];  
  9.                 matrix[last-offset][first] = matrix[last][last-offset];  
  10.                 matrix[last][last-offset] = matrix[i][last];  
  11.                 matrix[i][last] = top;  
  12.             }  
  13.         }  
  14.     }  


右旋代码:

  1. public static void rotateLeft(int[][] matrix,int n){  
  2.         for(int layer = 0;layer<n/2;layer++){  
  3.             int first = layer;  
  4.             int last = n-1-layer;  
  5.             for(int i=first;i<last;i++){  
  6.                 int offset = i-first;  
  7.                 int top = matrix[first][i];  
  8.                 matrix[first][i] = matrix[i][last];  
  9.                 matrix[i][last] = matrix[last][last-offset];  
  10.                 matrix[last][last-offset] = matrix[last-offset][first];  
  11.                 matrix[last-offset][first] = top;  
  12.             }  
  13.         }  
  14.     }  


测试用例:

  1. @Test  
  2.     public void test() {  
  3.         int[][] matrix = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};  
  4.         //ArrayUtil.rotateRight(matrix, 4);  
  5.         ArrayUtil.rotateLeft(matrix, 4);  
  6.         for(int i=0;i<4;i++){  
  7.             for(int j=0;j<4;j++){  
  8.                 if(j<3)  
  9.                     System.out.print(matrix[i][j]+" ");  
  10.                 else  
  11.                     System.out.println(matrix[i][j]);  
  12.             }  
  13.         }  
  14.     }  

测试结果:

左旋:

4 8 12 16
3 7 11 15
2 6 10 14
1 5 9 13

右旋:

13 9 5 1
14 10 6 2
15 11 7 3
16 12 8 4


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值