LeetCode#48. Rotate Image
来源:互联网 发布:算法书籍 编辑:程序博客网 时间:2024/05/16 01:32
- 题目:一个n*n的二维数组当做一张图片,顺时针旋转90度(将数组中的元素旋转90度)
- 难度:Medium
- 思路:从1*1、2*2、3*3举例分析旋转之前和旋转之后的元素下标变换规律 matrix[i][j] -> rotated[j][len-i-1] ,于是通过一个辅助数组来存储旋转后的值,然后将辅助数组赋值给matrix(not in place)
- 代码:
public class Solution { public void rotate(int[][] matrix) { if(matrix == null || matrix.length == 0) { return; } int n = matrix.length; int[][] result = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { result[j][n-i-1] = matrix[i][j]; } } for(int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { matrix[i][j] = result[i][j]; } } }}
题目中的follow up,要求在原数组中进行旋转(不能借助辅助数组)
public class Solution { public void rotate(int[][] matrix) { if(matrix == null || matrix.length == 0) { return; } int n = matrix.length; //1.先上下对折 for(int i = 0; i < n/2; i++){ for(int j = 0; j < n; j++){ int tmp = matrix[i][j]; matrix[i][j] = matrix[n-i-1][j]; matrix[n-i-1][j] = tmp; } } //2.再右下左上对折 for(int i = 0; i < n; i++){ for(int j = 0; j < i; j++){ int tmp = matrix[i][j]; matrix[i][j] = matrix[j][i]; matrix[j][i] = tmp; } } }}
阅读全文
0 0
- [LeetCode]48.Rotate Image
- LeetCode 48. Rotate Image
- LeetCode 48.Rotate Image
- LeetCode --- 48. Rotate Image
- [Leetcode] 48. Rotate Image
- [leetcode] 48. Rotate Image
- Leetcode 48. Rotate Image
- 48. Rotate Image LeetCode
- [LeetCode]48. Rotate Image
- leetcode 48. Rotate Image
- Leetcode 48. Rotate Image
- LeetCode 48. Rotate Image
- LeetCode *** 48. Rotate Image
- [LeetCode]48. Rotate Image
- LeetCode 48. Rotate Image
- LeetCode-48.Rotate Image
- [LeetCode] 48. Rotate Image
- LeetCode 48. Rotate Image
- JPEG压缩技术原理
- 有关链表的一些常见面试题
- 常见的浏览器以及内核
- 0MQ -- zmq_socket_monitor
- 淘淘商城系列——freemarker入门
- LeetCode#48. Rotate Image
- Java实现-打劫房屋1
- IntelliJ IDEA添加jar包
- 从安卓应用中解压数据到sdcard卡中
- Hdu2071 Max Num
- 2017 Android进程详解 进程保活
- 短信发送接口被恶意访问的网络攻击事件(一)紧张的遭遇战险胜
- Httpservlet cannot be resolved to a type的原因与解决方法
- 编写程序,实现使用键盘上的上下左右箭头控制界面上图片的移动。