LeetCode 48 Rotate Image(旋转图像)

翻译

给定一个 nn 的2D矩阵表示一个图像。

顺时针旋转90度。

跟进:
你可以就地完成它吗?

原文

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?

分析

尊重原创,一个很好的思路~

    public void rotate(int[][] matrix) {
        for (int i = 0; i < matrix.length / 2; i++) {
            swapArray(matrix, i, matrix.length - i);
        }
        for (int i = 0; i < matrix.length; ++i) {
            for (int j = i + 1; j < matrix[i].length; ++j) {
                swapValue(matrix, i, j);
            }
        }
    }

    void swapArray(int[][] matrix, int a, int b) {
        int[] tmp = matrix[a];
        matrix[a] = matrix[b];
        matrix[b] = tmp;
    }

    void swapValue(int[][] matrix, int i, int j) {
        int tmp = matrix[i][j];
        matrix[i][j] = matrix[j][i];
        matrix[j][i] = tmp;
    }

你可能感兴趣的:(LeetCode,emacs,rotate,48,ematrix)