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--
            }
        }
    }
    
  • 相关阅读:
    C# WPF定时器
    C#处理JSON数据
    SQL-乐观锁,悲观锁之于并发
    C# 集合-并发处理-锁OR线程
    C# 生成二维码,彩色二维码,带有Logo的二维码及普通条形码
    C# (事件触发)回调函数,完美处理各类疑难杂症!
    C# Lambda表达式
    C# 匿名方法
    浅谈C# 匿名变量
    鸡兔同笼
  • 原文地址:https://www.cnblogs.com/zhongju/p/13912735.html
Copyright © 2011-2022 走看看