[leetcode]Rotate Image

Rotate Image

You are given an n x n 2D matrix representing an image.

Rotate the image by 90 degrees (clockwise).

Follow up:
Could you do this in-place?

CC上的原题,大概还记得,时间复杂度O(n ^ 2),空间O(1)。

算法思路:

每一次转置相映成环的四个点。这四个点的坐标与n有关,可通过归纳法求出四个对应点的坐标关系

代码如下:

 1 public class Solution {
 2     public void rotate(int[][] matrix) {
 3         if(matrix == null || matrix.length == 0 ) return ;
 4         int n = matrix.length;
 5         int tem = 0;
 6         for(int i = 0; i < n >> 1; i++){
 7             for(int j = i; j < n - i - 1; j++){
 8                 tem = matrix[i][j];
 9                 matrix[i][j] = matrix[n - 1 - j][i];
10                 matrix[n - 1 - j][i] = matrix[n - 1 - i][n - 1- j];
11                 matrix[n - 1 - i][n - 1 - j] = matrix[j][n - 1 - i];
12                 matrix[j][n - 1 - i] = tem;
13             }
14         }
15     }
16 }

这四个坐标的对应关系真心蛋疼.....

 

posted on 2014-08-14 01:08  喵星人与汪星人  阅读(217)  评论(0编辑  收藏  举报