[LintCode] 旋转图像 Rotate Image

98 篇文章 0 订阅
3 篇文章 0 订阅
这篇博客介绍了如何90度顺时针旋转一个N×N的二维矩阵,包括给定的示例和解决挑战:在原地旋转图像。讨论了解决思路,即先水平翻转再斜向翻转。
摘要由CSDN通过智能技术生成

给定一个N×N的二维矩阵表示图像,90度顺时针旋转图像。
样例
给出一个矩形[[1,2],[3,4]],90度顺时针旋转后,返回[[3,1],[4,2]]
挑战
能否在原地完成?

You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Example
Given a matrix
[
[1,2],
[3,4]
]
rotate it by 90 degrees (clockwise), return
[
[3,1],
[4,2]
]
Challenge
Do it in-place.

思路:先以垂直线为中心水平翻转,再以逆对角线为中心斜向翻转。

public class Solution {
    /**
     * @param matrix: A list of lists of integers
     * @return: Void
     */
    public void rotate(int[][] matrix) {
        if(null == matrix || matrix.length == 0 || matrix[0].length == 0) return;
        int row = matrix.length;
        int col = matrix[0].length;
        if(row != col) return;
        for(int i = 0; i < row; i++) {
            for(int j = 0; j <= (col-1)/2; j++) {
                int temp = matrix[i][j];
                matrix[i][j] = matrix[i][col-1-j];
                matrix[i][col-1-j] = temp;
            }
        }
        for(int i = 0; i < row; i++) {
            for(int j = 0; j < row-i-1; j++) {
                int temp = matrix[i][j];
                matrix[i][j] = matrix[row-j-1][row-i-1];
                matrix[row-j-1][row-i-1] = temp;
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值