[C++]LeetCode: 68 Rotate Image
来源:互联网 发布:ubuntu运行安卓程序 编辑:程序博客网 时间:2024/05/21 11:31
题目:
Answer 2:转置法 (程序更简洁)
AC Code1:
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*N的图片的90度旋转(顺时针)
Answer 1: 中心旋转法
思路:根据题意,我们知道图片旋转是根据中心进行旋转的,于是我们将图片根据两条对角线划分为四个区域: A, A', A",A"'.然后依次替换四个位置的值,维护左上角的值。我们要做的就是将上边替换到右边,右边替换到下边,下边替换到左边。实际上完成的就是A ->A'->A"->A"'->A,实现四个区域的替换。所以外层循环从0~matrix.size()/2, 内层循环根据对角线从i ~ matrix.size() - i -1.我们唯一要注意的就是替换左边的确定,具体可以画图得到。可以参考如下的图加以理解。根据旋转中不变的长度来判断。
AC Code:
class Solution {public: void rotate(vector<vector<int> > &matrix) { int n = matrix.size(); for(int i = 0; i < n/2; i++) { for(int j = i; j < n - 1 - i; 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; } } return; }};
Answer 2:转置法 (程序更简洁)
思路1:先得到原矩阵的转置矩阵,之后从转置矩阵到旋转矩阵再reverse每行的元素即可。
思路2:先上下折叠原矩阵,再计算折叠矩阵的转置矩阵,即所求矩阵。
有图好理解,矩阵如下图:
Attention:
求转置矩阵时,将下三角矩阵和上三角矩阵元素交换。注意循环的里外层范围确定。
for(int i=0,n=matrix.size();i<n;++i){ for(int j=i+1;j<n;++j)
AC Code1:
class Solution {public: void rotate(vector<vector<int> > &matrix) { int n = matrix.size(); for(int i = 0; i < n; i++) { for(int j = i+1; j < n; j++) { swap(matrix[i][j], matrix[j][i]); } reverse(matrix[i].begin(), matrix[i].end()); } return; }};
class Solution {public: void rotate(vector<vector<int> > &matrix) { int n = matrix.size(); reverse(matrix.begin(), matrix.end()); for(int i = 0; i < n; i++) { for(int j = i + 1; j < n; j++) { swap(matrix[i][j], matrix[j][i]); } } return; }};
0 0
- [C++]LeetCode: 68 Rotate Image
- 【C++】【LeetCode】48. Rotate Image
- LeetCode c语言-Rotate Image
- [LeetCode] [C] 48. Rotate Image
- [C语言][LeetCode][48]Rotate Image
- leetcode刷题系列C++-rotate image
- LeetCode: Rotate Image
- [Leetcode] Rotate Image
- LeetCode : Rotate Image
- [LeetCode] Rotate Image
- leetcode 67: Rotate Image
- [leetcode] Rotate Image
- [Leetcode] Rotate Image
- [LeetCode]Rotate Image
- LeetCode-Rotate Image
- [leetcode] Rotate Image
- LeetCode - Rotate Image
- leetcode之Rotate Image
- 优化网站设计(三十):优化CSS sprites
- Javascript类继承浅析
- cocos2dx定时器时间不准
- javascript防反跳技术
- Javascript限制网页只能在微信内置浏览器中访问
- [C++]LeetCode: 68 Rotate Image
- Android 基于ImageSwitcher实现的左右切换图片
- MongoDB分页查询的方法及性能
- Android笔记----Service组件
- STM32微控制器启动代码
- 优化网站设计(三十一):不要在页面中缩放图片
- 《芈月传》发布会 孙俪:芈月比甄嬛更难演
- Java中转UTC时间字符串(含有T Z)为local时间
- 基于Android的计步器(Pedometer)的讲解(三)——CircleBar(圆形进度条)