LeetCode 048 Rotate Image

来源:互联网 发布:ipad 编程游戏 编辑:程序博客网 时间:2024/05/17 03:53
题目


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?

把图像顺时针旋转90°


思路


方法1:
用一个辅助数组放置数据
缺点:需要额外n*n的空间,需要n^2的时间

方法2:
把新的数组的坐标列出,直接按照公式来写
优点:普遍适用,容易想到。
缺点:数组下标混乱,每次要进行4个数据的移位转换,只需要一个temp


方法3
整体的通过数组找出关系
先把原数组转置,然后把每一行reverse
优点:
模块化 :转置模块,swap模块。

代码


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






0 0
原创粉丝点击