48. Rotate Image

来源:互联网 发布:淘宝开店收费吗2016 编辑:程序博客网 时间:2024/06/05 09:02

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?

思路: 先将数组以中间行为标准翻转,然后再以主对角线为标准交换对应元素。

时间复杂度:O(N*N)

空间复杂度: O(1)

<span style="font-size:14px;">public class Solution {    public void rotate(int[][] matrix) {        int n=matrix.length;        int temp;        //swap row i and n-1-i        for(int i=0;i<n/2;i++){            for(int j=0;j<n;j++){                temp=matrix[i][j];                matrix[i][j]=matrix[n-1-i][j];                matrix[n-1-i][j]=temp;            }        }            //        for(int i=1;i<n;i++){            for(int j=0;j<i;j++){                temp=matrix[i][j];                matrix[i][j]=matrix[j][i];                matrix[j][i]=temp;            }        }            }}</span>


0 0
原创粉丝点击