【002】LeetCode 48旋转图像

2. 题目48. 旋转图像

2.1 官方解析

讲的太复杂了,还是看下面的解析吧!原链接

2.2 解法1

(这道题自己的思路很清晰,但是在数组下标的确定上总是搞错!折腾了两个小时,真的是服了自己~)

直接交换

在这里插入图片描述

当时自己在做这道题的时候,一直困惑于下标的对应!一定要注意下标!!!

画个图,根据图上的坐标进行对应会容易很多,否则必定乱!

在这里插入图片描述

class Solution {
public:
    void rotate(vector<vector<int>>& matrix) {
        int length = matrix.size();
        for (int i = 0; i < length / 2; ++i) {
            for (int j = i; j < length - 1 - i; ++j) {
                int m = length - 1 - i;
                int n = length - 1 - j;
                
                int temp = matrix[i][j];
                matrix[i][j] = matrix[n][i];
                matrix[n][i] = matrix[m][n];
                matrix[m][n] = matrix[j][m];
                matrix[j][m] = temp;
            }
        }
    }
};

2.3 解法2

(这是在题解中看到的解法,是一种比较巧妙的办法!但如果在面试中遇到这道题,那大概率是想不到这种解法的,所以还是要掌握一种常规的解法!)

先上下交换,再对角线交换

在这里插入图片描述

class Solution {
public:
    void rotate(vector<vector<int>>& matrix) {
        int length = matrix.size();
        // 先上下交换
        for (int i = 0; i < length / 2; ++i) {
            // temp类型为vector<int> 本身就是一个指针
            vector<int> temp = matrix[i];   
            matrix[i] = matrix[length - i - 1];
            matrix[length - i - 1] = temp;
        }

        // 再对角线交换
        for (int i = 0; i < length; ++i) {
            for (int j = i + 1; j < length; ++j) {
                int temp = matrix[i][j];
                matrix[i][j] = matrix[j][i];
                matrix[j][i] = temp;
            }
        }
    }
};

2.4 解法3

做你爱吃的唐僧肉)的解法:逐层平移和偏移量的增加

采用分层来进行平移的方式,将矩阵的每一层都分开进行旋转,比如5*5的矩阵可以分为3层

在这里插入图片描述

旋转的时候,每四个矩阵块作为一组进行相应的旋转

在这里插入图片描述

在这里插入图片描述

可以看出,第二次旋转的时候比第一次旋转偏移了一格,这里我们使用add变量来记录矩阵块的偏移量,首先不考虑偏移量的时候写出左上角的坐标为(pos1,pos1),右上角的坐标为(pos1,pos2),左下角的坐标为(pos2,pos1),右下角的坐标为(pos2,pos2),则能够写出偏移之后对应的坐标

在这里插入图片描述

每次计算完一层之后,矩阵向内收缩一层,

在这里插入图片描述

所以有pos1 = pos1+1,pos2 = pos2-1,终止的条件为pos1 < pos2

class Solution {
public:
    void rotate(vector<vector<int>>& matrix) {
        int pos1 = 0, pos2 = matrix.size() - 1;
        int add, temp;
        while(pos1 < pos2) {
            add = 0;
            while(add < pos2 - pos1){
                temp = matrix[pos1][pos1+add];
                matrix[pos1][pos1+add] = matrix[pos2-add][pos1];
                matrix[pos2-add][pos1] = matrix[pos2][pos2-add];
                matrix[pos2][pos2-add] = matrix[pos1+add][pos2];
                matrix[pos1+add][pos2] = temp;
                add++;
            }
            pos1++;
            pos2--;
        }
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ClimberCoding

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值