[LeetCode]48. Rotate Image

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?

分析

题目要求将一个n x n 的二维矩阵进行顺时针90度旋转,直接思路是从外向内一圈一圈的交换数据,但是过于复杂也太慢。这个题目有个技巧,就是可以先将矩阵按照对角线转置,然后按照水平中线翻转一次即可。

1,2,3           9,6,3           7,4,1
4,5,6  =>       8,5,2  =>       8,5,2
7,8,9           7,4,1           9,6,3

源码

class Solution {
public:
    void rotate(vector<vector<int>>& matrix) {
        // 先将矩阵转置 再翻转每一列即可
        int rows = matrix.size();
        int cols = matrix[0].size();
        if(rows < 2) return;
        for(int row = 0; row < rows; row++) {
            // 只需遍历左上半角,并且对角线上元素不需要动,所以减1
            // 所以每行比较的元素都随着行数增加而减少
            for(int col = 0; col < (cols - row - 1); col++) {
                swap(matrix[row][col],matrix[rows - col - 1][cols - row - 1]);
            }
        }

        // 翻转各列
        for(int col = 0; col < cols; col++) {
            int middle = rows / 2;
            int i = 0;
            while(i < middle) {
                swap(matrix[i][col], matrix[rows - i - 1][col]);
                i++;
            }
        }
    }
    void swap(int& a, int& b) {
        a = a + b;
        b = a - b;
        a = a - b;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值