码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]Rotate Image

时间:2015-04-06 14:16:43      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:leetcode

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?
思路1:直接开辟一个数组,然后按照对应关系复制即可,空间和时间复杂度o(N*N)
代码1:
    public void rotate1(int[][] matrix) {//找出对应关系(i,j) -> (j,n-1-i)
        int n = matrix.length;
        int [][]tmp = new int[n][n];
        for(int i = 0; i < n; ++ i){
            for(int j =0; j < n; ++ j){
                tmp[j][n-i-1] = matrix[i][j];
            }
        }
        for(int i = 0; i < n; ++ i){
            for(int j =0; j < n; ++ j){
                matrix[i][j] = tmp[i][j];
            }
        }

     }

思路2:原地交换,先置换(i,j)到(j,i),然后对每行进行reverse 时间复杂度O(N*N),空间复杂度O(1)
代码2:
    public void rotate(int[][] matrix) {//inplace (i,j)->(j,i) reverse(每一行)
        int n = matrix.length;
        int temp;
        for(int i = 0; i < n; ++ i){
            for(int j =i; j < n; ++ j){
                temp = matrix[i][j];
                matrix[i][j] = matrix[j][i];
                matrix[j][i] = temp;
            }
        }

        int l,r;
        for(int i = 0;i < n; ++i){
            l = 0;
            r = n-1;
            while (l < r){
                temp = matrix[i][l];
                matrix[i][l] = matrix[i][r];
                matrix[i][r] = temp;
                l ++;
                r --;
            }
        }
    }


[LeetCode]Rotate Image

标签:leetcode

原文地址:http://blog.csdn.net/youmengjiuzhuiba/article/details/44901461

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!