zoukankan      html  css  js  c++  java
  • [LeetCode] 48. Rotate Image(旋转图片)

    Description

    You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).
    给你一个 n x n 的二维矩阵 matrix 表示一张图片,将该图片顺时针旋转 90°。

    You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
    你必须原地完成旋转操作,也就是说,你必须直接修改原先的二维数组。不要另外分配二维数组完成旋转。

    Examples

    Example 1

    Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
    Output: [[7,4,1],[8,5,2],[9,6,3]]
    

    Example 2

    Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
    Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]
    

    Example 3

    Input: matrix = [[1]]
    Output: [[1]]
    

    Example 4

    Input: matrix = [[1,2],[3,4]]
    Output: [[3,1],[4,2]]
    

    Constraints

    • matrix.length == n

    • matrix[i].length == n

    • 1 <= n <= 20

    • -1000 <= matrix[i][j] <= 1000

    Solution

    一开始一直在想一步到位的骚操作,最后没想出来,一翻 discussion 后恍然大悟,一步做不出来,为什么不分成两步做呢?

    顺时针 90° 旋转一张图片,需要以下两步(假设图片中心位于直角坐标原点):

    1. 整张图片以 x 轴翻转

    2. 整张图片以主对角线((y = -x))进行翻转

    代码如下:

    class Solution {
        fun rotate(matrix: Array<IntArray>): Unit {
            flipVertical(matrix)
            flipDiagonal(matrix)
        }
    
        private fun flipDiagonal(matrix: Array<IntArray>) {
            for (i in matrix.indices) {
                for (j in 0 until i) {
                    val t = matrix[i][j]
                    matrix[i][j] = matrix[j][i]
                    matrix[j][i] = t
                }
            }
        }
    
        private fun flipVertical(matrix: Array<IntArray>) {
            var i = 0
            var j = matrix.lastIndex
    
            while (i < j) {
                val t = matrix[i]
                matrix[i] = matrix[j]
                matrix[j] = t
    
                i++
                j--
            }
        }
    }
    
  • 相关阅读:
    Eclipse连接MySQL数据库(傻瓜篇)
    JMeter监控内存及CPU ——plugin插件监控被测系统资源方法
    fiddler抓取手机端的数据流量包
    python 字典(dictionary)一些方法
    python 循环语句
    Charles 抓 HTTPS 包
    python RSA 加密与签名
    从零开始做一个Jmeter性能测试
    [python之路]变量和字符编码
    [python之路]简单介绍
  • 原文地址:https://www.cnblogs.com/zhongju/p/13912735.html
Copyright © 2011-2022 走看看