Leetcode: Rotate Image
来源:互联网 发布:java写二维码 编辑:程序博客网 时间:2024/05/22 03:30
题目:
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?
思路分析:
最笨的方法,重新开辟一个矩阵空间,做旋转。(题目要求最好能就地旋转)
更好的方法:先将矩阵上下对折,然后再沿对角线对折。
例如:
1 2 3 7 8 9 7 4 14 5 6 -> 4 5 6 -> 8 5 27 8 9 1 2 3 9 6 3
OK,开始写代码!
C++参考代码:
class Solution{public: void rotate(vector<vector<int> > &matrix) { if (matrix.empty()) return; int rows = int(matrix.size()); int cell = 0; //上下对折 for (int i = 0; i < rows / 2; ++i) { for (int j = 0; j < rows; ++j) { cell = matrix[i][j]; matrix[i][j] = matrix[rows - i - 1][j]; matrix[rows - i - 1][j] = cell; } } //对角线对折 for (int i = 0; i < rows; ++i) { for (int j = 0; j < i; ++j) { cell = matrix[i][j]; matrix[i][j] = matrix[j][i]; matrix[j][i] = cell; } } }};
0 0
- 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
- LeetCode - Rotate Image
- Leetcode: Rotate Image
- LeetCode:Rotate Image
- Leetcode: Rotate Image
- Leetcode Rotate Image
- leetcode Rotate Image
- Checked异常和Runtime异常
- 2015-04-12记录
- EasyUI的面板和Ajax的结合使用
- 全排列的生成算法
- ajaxterm使用
- Leetcode: Rotate Image
- iOS进阶面试题----经典10道
- 5原因致西欧列强跟中国混
- 七擒七纵是真是假
- 关于树形结构建立过程中动态申请的节点空间
- MFC调不出运行程序,调试是提示“unhandle exception****(0xc0000005)”
- hdu 2066最短路 dijkstra 及其优先队列优化
- notepad++插件及配置相关
- 插入法排序(含二分法)