资讯专栏INFORMATION COLUMN

LeetCode[48] Rotate Image

sanyang / 3017人阅读

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 rotate(int[][] matrix) {
        int n = matrix.length;
        for(int layer = 0; layer < n / 2; layer ++) {
            int start = layer;
            int end = n - 1 - start;
            for(int i = start; i < end; i ++) {
                int offset = i - start;
                int temp = matrix[start][i];
                //left to top;
                matrix[start][i] = matrix[end - offset][start];
                //bottom to left;
                matrix[end - offset][start] = matrix[end][end - offset];
                //right to bottm;
                matrix[end][end - offset] = matrix[i][end];
                //top to right;
                matrix[i][end] = temp; 
            }
        }

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

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

相关文章

  • [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
  • leetcode 48 Rotate Image

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

    kgbook 评论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元查看
<