leetcode--Rotate Image
2015-06-06 15:55
597 查看
ou 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度。
你能在原地操作吗?
分类:数组
解法1:如下图,首先沿逆对角线翻转一次,然后按x轴中线翻转一次。
public class Solution {
public void rotate(int[][] matrix) {
int n = matrix.length;
int[][] res = new int
;
for(int i=0;i<n-1;i++){
for(int j=0;j<n-i;j++){
swap(matrix,i,j,n-1-j,n-1-i);
}
}
for(int i=0;i<n/2;i++){
for(int j=0;j<n;j++){
swap(matrix,i,j,n-i-1,j);
}
}
}
public void swap(int[][] matrix,int x1,int y1,int x2,int y2){
int t = matrix[x1][y1];
matrix[x1][y1] = matrix[x2][y2];
matrix[x2][y2] = t;
}
}
解法2:利用额外n*n空间。遍历每一行,将这一行存储到申请的新数组的每一列。
Rotate the image by 90 degrees (clockwise).
Follow up:
Could you do this in-place?
题意:给定一个n*n二维数组,将其旋转90度。
你能在原地操作吗?
分类:数组
解法1:如下图,首先沿逆对角线翻转一次,然后按x轴中线翻转一次。
public class Solution {
public void rotate(int[][] matrix) {
int n = matrix.length;
int[][] res = new int
;
for(int i=0;i<n-1;i++){
for(int j=0;j<n-i;j++){
swap(matrix,i,j,n-1-j,n-1-i);
}
}
for(int i=0;i<n/2;i++){
for(int j=0;j<n;j++){
swap(matrix,i,j,n-i-1,j);
}
}
}
public void swap(int[][] matrix,int x1,int y1,int x2,int y2){
int t = matrix[x1][y1];
matrix[x1][y1] = matrix[x2][y2];
matrix[x2][y2] = t;
}
}
解法2:利用额外n*n空间。遍历每一行,将这一行存储到申请的新数组的每一列。
public class Solution { public void rotate(int[][] matrix) { int n = matrix.length; int[][] res = new int ; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ res[j][n-i-1] = matrix[i][j]; } } for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ matrix[i][j] = res[i][j]; } } } }
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序
- 二叉查找树
- [原创]java局域网聊天系统