[leetcode]Rotate Image

新博文地址:[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?

 我没有想到in-place的方法,因此开辟了O(n^2)的空间,显然是不满足的要求的。

代码如下:

    public void rotate(int[][] matrix) {
        int n = matrix.length;
        if(n <= 1){
            return;
        }
        int[][] tem = new int[n][n];
        for(int i = 0; i < n; i++){
            for(int j = 0; j < n; j++){
                tem[j][n - 1 - i] = matrix[i][j];
            }
        }
        matrix = tem;//这里错了
    }

 这个答案是WA的,具体原因涉及到了java中值传递和引用传递的知识,大家可以看这篇小结

因此,我们需要人为的将matrix进行赋值:

    public void rotate(int[][] matrix) {
        int n = matrix.length;
        if(n <= 1){
            return;
        }
        int[][] tem = new int[n][n];
        for(int i = 0; i < n; i++){
            for(int j = 0; j < n; j++){
                tem[j][n - 1 - i] = matrix[i][j];
            }
        }
        for(int i = 0; i < n; i++){
            for(int j = 0; j < n; j++){
                matrix[i][j] = tem[i][j];
            }
        }
    }

 这样就顺利AC了,不过不满足题中所说的in-place条件,第二遍再优化吧。新博文中采用了in-place的方法,请移步[leetcode]Rotate Image

你可能感兴趣的:(LeetCode)