leetcode-48. Rotate Image

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?

要求要做原地变换。这里其实需要找规律,如果一个一个移动的话虽然理论上可以,但是实在太复杂了。

  • 顺时针旋转:
    • 先沿着对角线翻转,然后在竖直方向翻转一下就可以了。
  • 逆时针旋转:
    • 先竖直方向翻转,然后在沿着对角线反正一下就可以了。

答案来源

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

你可能感兴趣的:(JAVA,leetcode,欠练的题目,leetcode,java)