LeetCode Rotate Image
来源:互联网 发布:阿里数据分析 面试 编辑:程序博客网 时间:2024/06/05 03:33
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?
First use a naive solution: create a new 2D matrix and use the following formula to copy the data.
result[j[n - i - 1] = marix[i][j];
public class Solution { public void rotate(int[][] matrix) { int[][] result = new int[matrix.length][matrix.length]; for(int i = 0; i < matrix.length; i++){ for(int j = 0; j < matrix[i].length; j++){ result[j][matrix.length - 1 - i] = matrix[i][j]; } } for(int i = 0; i < matrix.length; i++){ for(int j = 0; j < matrix.length; j++){ matrix[i][j] = result[i][j]; } } }}
Then consider the in-place case.
The formula becomes:
matrix[i][j] = matrix[n - 1 - j][i];
So the code is as follows:
public class Solution { public void rotate(int[][] matrix) { int n = matrix.length; int[][] result = new int[n][n]; for(int i = 0; i < Math.ceil(((double) n) / 2); i++){ for(int j = 0; j < n / 2; j++){ int temp = matrix[i][j]; matrix[i][j] = matrix[n - 1 - j][i]; matrix[n - 1 - j][i] = matrix[n - 1 - i][n - 1 - j]; matrix[n - 1 - i][n - 1 - j] = matrix[j][n - 1 - i]; matrix[j][n - 1 - i] = temp; } } }}
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
- extjs_08_界面布局
- java集成开发环境构建
- windows7 中 wacom数位板如何关闭点击水波 和长按右键这两个特效
- shell之“>/dev/null 2>&1” 详解
- 结束了
- LeetCode Rotate Image
- js with onsubmit
- 什么时候你才会从重复中惊醒?
- 960H 、SDI和百万高清,谁会率先出局?
- 个VS编译器(cl.exe)命令行编译的例子
- Android 手势锁的实现 让自己的应用更加安全吧
- 并行fp-growth图解(mahout)
- 红外摄像机产品走势及市场现状分析
- coj-Checker Challenge