资讯专栏INFORMATION COLUMN

leetcode 48 Rotate Image

kgbook / 1352人阅读

摘要:题目详情这道题目要求我们对一个正方形矩阵进行顺时针度的翻转。并且要求不声明额外的空间,不能新建二维数组。输入数组旋转后的输入数组想法这道题因为要求在位。所以我们需要找到一种解法,使得每次操作都是交换两个元素的位置,最后实现整个矩阵的旋转。

题目详情
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Note:
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.

这道题目要求我们对一个正方形矩阵进行顺时针90度的翻转。并且要求不声明额外的空间,不能新建二维数组。

Example 2:
输入数组matrix =
[
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
],
旋转后的输入数组:
[
[15,13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7,10,11]
]

想法

这道题因为要求“在位”。所以我们需要找到一种解法,使得每次操作都是交换两个元素的位置,最后实现整个矩阵的旋转。

我们先对整个矩阵进行上下翻转。如下

123 789

456 -> 456

789 123

然后对矩阵进行沿对角线的翻转。如下

789 741

456 -> 852

123 963

就得到了我们最后旋转90度的矩阵。

解法
    //先将上下翻转,再沿对角线翻转
    public void rotate(int[][] matrix) {
        int height = matrix.length;
        int width = matrix[0].length;
        //上下翻转
        for(int i=0;i           
               
                                           
                       
                 

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/68514.html

相关文章

  • LeetCode[48] Rotate Image

    LeetCode[48] Rotate Image 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? 复杂度O(N^2),O(1) 代码 public void ro...

    sanyang 评论0 收藏0
  • [LeetCode] 48. Rotate Image

    Problem You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees (clockwise). Note: You have to rotate the image in-place, which means you have to modify the input 2D mat...

    Warren 评论0 收藏0
  • leetcode48 Rotate Image 90度旋转数组

    摘要:每一次的旋转,其实都是正方形上的四个元素之间的相互替换。所以本质上我们只需遍历每种长度正方形上的一条边,就可以完成这个正方形的旋转。最后实现整个数组矩阵的旋转代表正方形的起始位置,即,,即,代表当前正方形上的一条边上的一个点。 题目要求 You are given an n x n 2D matrix representing an image. Rotate the image b...

    melody_lql 评论0 收藏0
  • leetcode 部分解答索引(持续更新~)

    摘要:前言从开始写相关的博客到现在也蛮多篇了。而且当时也没有按顺序写现在翻起来觉得蛮乱的。可能大家看着也非常不方便。所以在这里做个索引嘻嘻。顺序整理更新更新更新更新更新更新更新更新更新更新更新更新更新更新更新更新 前言 从开始写leetcode相关的博客到现在也蛮多篇了。而且当时也没有按顺序写~现在翻起来觉得蛮乱的。可能大家看着也非常不方便。所以在这里做个索引嘻嘻。 顺序整理 1~50 1...

    leo108 评论0 收藏0
  • [Leetcode] Rotate Image 旋转图片

    摘要:交换法复杂度时间空间思路为了实现这题,我们要用交换的方法,顺序是左上先和左下交换,然后左上和右下交换,然后左上和右上交换。和类似,我们通过圈数来控制内外的顺序。代码计算圈数左上和左下交换左上和右下交换左上和右上交换 Rotate Image You are given an n x n 2D matrix representing an image. Rotate the image...

    Brenner 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<