Leetcode刷题记——48. Rotate Image(旋转图像)

来源:互联网 发布:淘宝添加到桌面没有了 编辑:程序博客网 时间:2024/05/01 09:30

一、题目叙述:

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?

Subscribe to see which companies asked this question.

给一个n*n的数组矩阵代表一个2D图像,顺时针旋转90度,得到的图像

二、解题思路:

Medium题,简单举个例子即可得出规律。

如:

[2,5                     [8,  2              

8,,4]     旋转后为 4,5]  即,旋转后的第一行为旋转前第一列的逆序;第二行为第二列的逆序。。。以此类推。

(1)创建中间二维数组res,按上述规律为res赋值。

(2)将res内容复制回原数组即可。

三、源码:

import java.util.ArrayList;  import java.util.Arrays;import java.util.List;    public class Solution  {  public void rotate(int[][] matrix) {int n = matrix.length;if (n == 0) return;int [][] res = new int[n][n];for (int i = 0; i < n; i++)for (int j = 0; j < n; j++)res[i][j] = matrix[n-j-1][i];for (int i = 0; i < n; i++)for (int j = 0; j < n; j++)matrix[i][j] = res[i][j];System.out.print(Arrays.deepToString(matrix));return;    }    public static void main(String args[])          {                        //String a = "";    //String b = "";      //  int[] digits = {0};              Solution solution = new Solution();              int[][] abc = {{2}};        //  int[] b = {2,3,4};         // for(int i = 0; i < abc.length; i ++)              solution.rotate(abc);   //       System.out.print(solution.rotate(abc));                    }      }  


0 0