ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

[LeetCode] 48. Rotate Image(旋转图片)

2020-11-02 09:01:33  阅读:173  来源: 互联网

标签:Rotate matrix 48 Image rotate image Output Input Example


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--
        }
    }
}

标签:Rotate,matrix,48,Image,rotate,image,Output,Input,Example
来源: https://www.cnblogs.com/zhongju/p/13912735.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有