[48]Rotate Image

来源:互联网 发布:sgd算法 矩阵分解 编辑:程序博客网 时间:2024/04/30 22:33

【题目描述】

You are given an n x n 2D matrix representing an image.

Rotate the image by 90 degrees (clockwise).

【思路】

如果逐步旋转的话速度太慢,考虑先沿主对角线翻转,然后再沿水平中线翻转一次。

【代码】

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


0 0
原创粉丝点击