Leetcode 48 Rotate Image

来源:互联网 发布:修改php端口号 编辑:程序博客网 时间:2024/05/29 08:21

题目:

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?

思路:

思路就是先进行对角翻转,然后作左右对称

1  2  3             4  5  67  8  9

对角翻转后如下,

1  4  72  5  83  6  9

左右翻转如下

7  4  18  5  29  6  3

代码:

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


0 0