[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;
            }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值