[Leetcode]Rotate Image
来源:互联网 发布:好的枕头 知乎 编辑:程序博客网 时间:2024/05/18 19:37
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?
利用异或(XOR),实现以不需要temp变量的方式完成交换。
例如:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
首先是最外面一圈,最先按顺时针交换的4个数是(把matrix[0][0] = 1存给temp,把matrix[3][0] = 13给matrix[0][0],把matrix[3][3] = 16给matrix[3][0],把matrix[0][3] = 4给matrix[3][3],把temp = 1给matrix[0][3])
1 4
13 16
接着是需要交换的2、9、15、8
1 2 4
8
9
13 15 16
依次往下,把第一圈交换完了,再往里圈走。
class Solution {public: void rotate(vector<vector<int> > &matrix) { if(matrix.size() != 1) { int size = 0; size = (matrix.size() - 1) / 2; int n = matrix.size() - 1; for(int i = 0; i <= size; i++) { for(int j = i; j <= n - 1 - i; j++) { matrix[i][j] ^= matrix[n - j][i]; matrix[n - j][i] ^= matrix[i][j]; matrix[i][j] ^= matrix[n - j][i]; matrix[n - j][i] ^= matrix[n - i][n - j]; matrix[n - i][n - j] ^= matrix[n - j][i]; matrix[n - j][i] ^= matrix[n - i][n - j]; matrix[n - i][n - j] ^= matrix[j][n - i]; matrix[j][n - i] ^= matrix[n - i][n - j]; matrix[n - i][n - j] ^= matrix[j][n - i]; } } } }};
代码似乎还是有点冗余,如果各位有更好的解法,希望可以共享·~谢谢啦·~
附:利用temp变量的解法
class Solution {public: void rotate(vector<vector<int> > &matrix) { if(matrix.size() != 1) { int size = 0; size = (matrix.size() - 1) / 2; int n = matrix.size() - 1; for(int i = 0; i <= size; i++) { for(int j = i; j <= n - 1 - i; j++) { int temp = matrix[i][j]; matrix[i][j] = matrix[n - j][i]; matrix[n - j][i] = matrix[n - i][n - j]; matrix[n - i][n - j] = matrix[j][n - i]; matrix[j][n - i] = temp; } } } }
注:以上两解法,在Leetcode上,运行时间均为12ms。
本文不详尽或错误之处,请各位不吝言辞,多多指教~谢谢~
作者:Louise http://blog.csdn.net/yupingliu
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
- 运营初期应该选用什么样的机器人
- 免费接口API
- 模板——大数相乘
- 软件设计漫谈之二:设计模式只是一把锤子!
- SVN源码服务器搭建-详细教程
- [Leetcode]Rotate Image
- QString和CString 相互转换
- 教你如何修改树莓派的时区和网络对时
- 我与编程
- 软件设计漫谈之三:30分钟掌握面向对象类的设计原则
- Android设计模式学习日记04--单例模式
- UVa:11987 Almost Union-Find(并查集)
- 面向用户的图片格式选择
- Codeforces Round #237 (Div. 2) A. Valera and X(模拟题)