Rotate Image
来源:互联网 发布:silverlight mac版本 编辑:程序博客网 时间:2024/06/07 17:38
一、问题描述
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度。原理如下:先上下翻转,再交换对角元素即可。
* 1 2 3 7 8 9 7 4 1 * 4 5 6 => 4 5 6 => 8 5 2 * 7 8 9 1 2 3 9 6 3
三、代码
class Solution {public: void rotate(vector<vector<int>>& matrix) { reverse(matrix.begin(), matrix.end()); for(int i = 0; i < matrix.size();++i){ for(int j = i + 1; j < matrix[i].size();++j){ swap(matrix[i][j],matrix[j][i]); } } }};
在评论区看到另外一种思路:先左右翻转,然后交换对角元素。
* 1 2 3 3 2 1 3 6 9 * 4 5 6 => 6 5 4 => 2 5 8 * 7 8 9 9 8 7 1 4 7
void anti_rotate(vector<vector<int> > &matrix) { for (auto vi : matrix) reverse(vi.begin(), vi.end()); for (int i = 0; i < matrix.size(); ++i) { for (int j = i + 1; j < matrix[i].size(); ++j) swap(matrix[i][j], matrix[j][i]); }}
1 0
- Rotate Image
- Rotate Image
- Rotate Image
- Rotate Image
- Rotate Image
- Rotate Image
- Rotate Image
- Rotate Image
- Rotate Image
- Rotate Image
- Rotate Image
- Rotate Image
- Rotate Image
- Rotate Image
- Rotate Image
- Rotate Image
- Rotate Image
- Rotate Image
- Java——基本数据类型常用的一些方法
- springmvc的ModelAttribute注解
- 沟通的目的
- PAT 1013. Battle Over Cities (25)(孤岛的个数,DFS或者BFS)
- schedule、scheduleAtFixedRate和scheduleWithFixedDelay的区别
- Rotate Image
- 运用 三种 原生 谷歌 阿里 解析和生成json
- 对称加密和非对称加密
- 通过Controller返回到jsp页面后,图片、css样式等消失了
- iOS扬声器和听筒模式的切换以及距离传感器红外感应的设置
- lintcode-螺旋矩阵 II
- activemq安全设置—设置admin的用户名和密码
- Error:Jack is required to support java 8 language features. Either enable Jack or remove sourceCompa
- 25. Reverse Nodes in k-Group(23.53%)