0
点赞
收藏
分享

微信扫一扫

[LeetCode]Rotate Image


Question
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?

本题难度Medium。

【题意】
对一个正方形矩阵进行顺时针旋转90度。

【复杂度】
时间 O(N) 空间 O(1)

【思路】
第一步:镜像对换
如:

1  2  3
4 5 6
7 8 9
->
9 6 3
8 5 2
7 4 1

第二步:上下对换
如:

9  6  3
8 5 2
7 4 1
->
7 4 1
8 5 2
9 6 3

这就是follow up 说的in-place。

【注意】
不要使用诸如:

void swap(int a,int b){
int tmp=a;
a=b;
b=a;
}

swap是传值,但对matrix没有影响。

【代码】

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


举报

相关推荐

0 条评论