【LeetCode】48. Rotate Image解法及注释
来源:互联网 发布:打印机怎么网络共享 编辑:程序博客网 时间:2024/05/24 01:44
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?
【分析】
此题要求将一个二维矩阵旋转90度,官方认证的难度是“Medium”,个人觉得此题达不到这个Level。既然是旋转矩阵,寻找规律就很重要了,简单在草稿上画一下:
我们可以看出:对于一个N阶矩阵,旋转过后,原来的“行”变成了“列”,第i行变成了第N-i-1列,即A[i][j]-->A[j][N-i-1],但是,直接通过一重循环是不能完成转换的,细想:在第0行与第2列的交换中,我们已经改变了原来矩阵第1行中“6”和第二行“9”的位置,如此,交换后已经不满足即A[i][j]-->A[j][N-i-1]的规律,因此,在不使用额外空间的情况下通过一次变换达到目标不太现实。
鉴于上述分析,我们可以将行列的变换分步实现:首先将矩阵的行转换成列,然后再交换列的顺序,值得注意的是,第二步中列顺序的交换是一种“对折”,第0列与最后一列交换,第一列与倒数第二列交换。
A[i][j]-->A[j][N-i-1]转换为:A[i][j]-->A[j][i]-->A[j][N-i-1]
【解法】
根据上述分析,很容易写出程序:
class Solution {public: void rotate(vector<vector<int>>& matrix) { if (matrix.size()==0)//矩阵为空,直接返回 return; int n = matrix.size();//求取矩阵的阶数 //沿主对角线进行交换,行列变换 for (int i=0; i<n; i++) { for (int j=0; j<i; j++) swap(matrix[i][j], matrix[j][i]); } //列序变换 for (int i=0, j=n-1; i<j; i++,j--) { for (int k=0; k<n; k++) swap(matrix[k][i], matrix[k][j]); } }};
0 0
- 【LeetCode】48. Rotate Image解法及注释
- leetcode-48.Rotate Image 解法
- leetcode:Rotate Image菜鸟解法
- Rotate Image问题及解法
- [LeetCode]48.Rotate Image
- LeetCode 48. Rotate Image
- LeetCode 48.Rotate Image
- LeetCode --- 48. Rotate Image
- [Leetcode] 48. Rotate Image
- [leetcode] 48. Rotate Image
- Leetcode 48. Rotate Image
- 48. Rotate Image LeetCode
- [LeetCode]48. Rotate Image
- leetcode 48. Rotate Image
- Leetcode 48. Rotate Image
- LeetCode 48. Rotate Image
- LeetCode *** 48. Rotate Image
- [LeetCode]48. Rotate Image
- 传值和传址
- bzoj 3329: Xorequ
- android activity显示不出布局
- Android动态部署五:如何从插件apk中启动Service
- STL源码剖析---vector
- 【LeetCode】48. Rotate Image解法及注释
- CentOS 7 U盘 启动盘安装遇到的问题
- 指针内存分配
- 四种常见的 POST 提交数据方式
- 文件指针/句柄、文件描述符、文件路径的相互转换
- [iOS Crash文件分析]-如何使用symbolicatecrash工具
- python进阶学习笔记(三)数据库支持
- 搭建SSL,让Apache支持Https
- MySQL 配置优化