LeetCode - Rotate Image

来源:互联网 发布:网上贷款软件排行 编辑:程序博客网 时间:2024/06/06 05:57

https://leetcode.com/problems/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?

这道题就是分圈,然后每圈每个变量依次转,就是在转的时候注意目标位置的下标,这个下标一个是当前圈数(代码中的i)的函数,一个是当前在圈中的位置(代码中的j)的函数

注意画个图把这些下标都写出来,不然非常容易乱。

代码如下:

    public void rotate(int[][] matrix) {        if(matrix==null || matrix.length==0) return;        int size = matrix.length;        int layer = size/2;        for(int i=0; i<layer; i++){            for(int j=i; j<(size-i-1); j++){                int tmp = matrix[i][j];                matrix[i][j] = matrix[size-j-1][i];                matrix[size-j-1][i] = matrix[size-i-1][size-j-1];                matrix[size-i-1][size-j-1] = matrix[j][size-i-1];                matrix[j][size-i-1] = tmp;            }        }    }

空间复杂度O(1),时间复杂度O(n^2)

0 0