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?

旋转一个n * n的二维数组,要求in-place完成。in-place的意思就是不要开辟额外的空间。我们可以从最外层开始旋转,一直到最里面的一层。长度为n的数组一共要旋转n / 2次。每一层旋转对应一个for循环。代码如下:
public class Solution {
    public void rotate(int[][] matrix) {
        if(matrix == null || matrix.length == 1) return;
        int m = matrix.length;
        int times = m / 2;
        for(int layer = 0; layer < times; layer++) {
            int first = layer;
            int last = m - 1 - layer;
            for(int i = first; i < last; i++) {
                int top = matrix[first][i];
                matrix[first][i] = matrix[m - 1 - i][first];
                matrix[m - 1 - i][first] = matrix[m - first - 1][m - 1 - i];
                matrix[m - first - 1][m - 1 - i] = matrix[i][m - 1 - first];
                matrix[i][m - 1 - first] = top;
            }
        }
    }
}

猜你喜欢

转载自kickcode.iteye.com/blog/2275136