1.6 题目:
给定一个N*N阶的矩阵,左或右旋转90度,不要使用额外的空间。
解法:
最优的复杂度为O(N^2)
左旋代码:
- public static void rotateRight(int[][] matrix,int n){
- for(int layer = 0;layer< n/2;layer++){
- int first = layer;
- int last = n-1-layer;
- for(int i=first;i<last;i++){
- int offset = i-first;
- int top = matrix[first][i];
- matrix[first][i] = matrix[last-offset][first];
- matrix[last-offset][first] = matrix[last][last-offset];
- matrix[last][last-offset] = matrix[i][last];
- matrix[i][last] = top;
- }
- }
- }
右旋代码:
- public static void rotateLeft(int[][] matrix,int n){
- for(int layer = 0;layer<n/2;layer++){
- int first = layer;
- int last = n-1-layer;
- for(int i=first;i<last;i++){
- int offset = i-first;
- int top = matrix[first][i];
- matrix[first][i] = matrix[i][last];
- matrix[i][last] = matrix[last][last-offset];
- matrix[last][last-offset] = matrix[last-offset][first];
- matrix[last-offset][first] = top;
- }
- }
- }
测试用例:
- @Test
- public void test() {
- int[][] matrix = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
- //ArrayUtil.rotateRight(matrix, 4);
- ArrayUtil.rotateLeft(matrix, 4);
- for(int i=0;i<4;i++){
- for(int j=0;j<4;j++){
- if(j<3)
- System.out.print(matrix[i][j]+" ");
- else
- System.out.println(matrix[i][j]);
- }
- }
- }
测试结果:
左旋:
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