LeetCode[48] 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?

复杂度
O(N^2),O(1)

代码

  public void rotate(int[][] matrix) {
        int n = matrix.length;
        for(int layer = 0; layer < n / 2; layer ++) {
            int start = layer;
            int end = n - 1 - start;
            for(int i = start; i < end; i ++) {
                int offset = i - start;
                int temp = matrix[start][i];
                //left to top;
                matrix[start][i] = matrix[end - offset][start];
                //bottom to left;
                matrix[end - offset][start] = matrix[end][end - offset];
                //right to bottm;
                matrix[end][end - offset] = matrix[i][end];
                //top to right;
                matrix[i][end] = temp; 
            }
        }

hellolittleJ17
10 声望11 粉丝