Leetcode—48. 旋转图像【中等】

2023每日刷题(九十三)

Leetcode—48. 旋转图像

Leetcode—48. 旋转图像【中等】_第1张图片

数学算法思想

Leetcode—48. 旋转图像【中等】_第2张图片
Leetcode—48. 旋转图像【中等】_第3张图片

实现代码

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

运行结果

Leetcode—48. 旋转图像【中等】_第4张图片

翻转代替旋转算法思想

Leetcode—48. 旋转图像【中等】_第5张图片

实现代码

class Solution {
public:
    void rotate(vector<vector<int>>& matrix) {
        int n = matrix.size();
        // 上下翻转
        for(int i = 0; i < n / 2; i++) {
            for(int j = 0; j < n; j++) {
                swap(matrix[i][j], matrix[n - 1 - i][j]);
            }
        }
        // 对角线翻转
        for(int i = 0; i < n; i++) {
            for(int j = 0; j < i; j++) {
                swap(matrix[i][j], matrix[j][i]);
            }
        }
    }
};

运行结果

Leetcode—48. 旋转图像【中等】_第6张图片

之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!

你可能感兴趣的:(LeetCode刷题,leetcode,算法,职场和发展,c++,经验分享)