48. Rotate Image
2016-07-19 09:14
232 查看
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?
例如
变成
观察规律,新阵(i,j)=原阵(j,n-1-i)
public class Solution {
public void rotate(int[][] matrix)
{
int row=matrix.length;
if(row<1)
return ;
int[][] arr=new int[row][row];
for(int i=0;i<row;i++)
System.arraycopy(matrix[i], 0, arr[i], 0, row);
for(int i=0;i<row;i++)
for(int j=0;j<row;j++)
matrix[j][row-1-i]=arr[i][j];
}
}
-----------------------------------------------------------------------------------------------------------------------------
in-place方法,摘自https://discuss.leetcode.com/topic/6796/a-common-method-to-rotate-the-image
here give a common method to solve the image rotation problems.
Rotate the image by 90 degrees (clockwise).
Follow up:
Could you do this in-place?
例如
1 | 2 | 3 |
4 | 5 | 6 |
7 | 8 | 9 |
7 | 4 | 1 |
8 | 5 | 2 |
9 | 6 | 3 |
public class Solution {
public void rotate(int[][] matrix)
{
int row=matrix.length;
if(row<1)
return ;
int[][] arr=new int[row][row];
for(int i=0;i<row;i++)
System.arraycopy(matrix[i], 0, arr[i], 0, row);
for(int i=0;i<row;i++)
for(int j=0;j<row;j++)
matrix[j][row-1-i]=arr[i][j];
}
}
-----------------------------------------------------------------------------------------------------------------------------
in-place方法,摘自https://discuss.leetcode.com/topic/6796/a-common-method-to-rotate-the-image
here give a common method to solve the image rotation problems.
/* * clockwise rotate * first reverse up to down, then swap the symmetry * 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 */ 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]); } } /* * anticlockwise rotate * first reverse left to right, then swap the symmetry * 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]); } }
相关文章推荐
- Execution failed for task ':app:transformClassesWithDexForDebug'和UnsupportedClassVersionError
- spring(九):基于配置的spring aop
- GDB调试,makefile使用,linux相关
- SSH项目开发中表现层和业务逻辑层之间的传值问题
- floodfill算法
- 实习见闻(1)——第一天
- Android中SQLite应用详解
- 解决vs2008无法切换设计视图的问题
- js动态添加事件-事件委托
- mysql备份之xtrabackup
- 杭电1004
- ROS学习之 cpp名字和节点信息
- 代码优化
- Hadoop HDFS概念学习系列之熟练掌握HDFS的Shell访问(十五)(博主推荐)
- MySQL · 特性分析 · 内部临时表
- Java中String类的一些用法 和含义
- 专访|HPE软件部中国区总经理李时:HPE引领IT战略新形态
- #500-1 类和对象
- Intellij 导出JAR包
- EXTJS中TreePanel和TabPanel配合使用的问题