48Rotate Image
来源:互联网 发布:沙丁鱼流量软件 编辑:程序博客网 时间:2024/04/30 22:07
题目链接:https://leetcode.com/problems/rotate-image/
题目:
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?
解题思路:
1 2 3 45 6 7 89 10 11 1213 14 15 16
- 通过举例子可以看出规律:第一行(行号:0)移到最后一列(列号:3 = 3 - 0),第二行(行号:1)变成第二列(列号:2 = 3 -
1)……最后一行(行号:3)变成第一列(列号:0 = 3 - 3)。 - 也就是说,
变化后的列号 = 最大列号 - 变化前的行号
。变化后的行号 = 变化前的列号
此种解法在复制元素的过程中会破坏原本的元素,因而必须借用额外的空间,将 matrix 数组中的全部元素复制到一个临时数组中。
public class Solution { public void rotate(int[][] matrix) { int len = matrix[0].length; int[][] temp = new int[len][len]; for(int i = 0; i < len; i ++) { for(int j = 0; j < len; j ++) temp[i][j] = matrix[i][j]; } for(int i = 0; i < len; i ++) { for(int j = 0; j < len; j ++) matrix[j][len - 1 - i] = temp[i][j]; } }}
20 / 20 test cases passed.Status: AcceptedRuntime: 272 ms
方法更新:就地转换
题目希望我们能不使用额外空间。因而有了方法二。
解题思路:
参考链接:http://blog.csdn.net/kenden23/article/details/17200067
1 2 3 45 6 7 89 10 11 1213 14 15 16
矩阵从外到内,每一圈是一个外循环。例如:
第一个循环:1 2 3 45 89 1213 14 15 16第二个循环:6 710 11
内循环为:
包含三个内循环:*1 #2 @3 *4@5 #8#9 @12*13 @14 #15 *16
public class Solution { public void rotate(int[][] matrix) { int len = matrix.length; for(int i = 0, j = len - 1; i < j; i ++, j --) { for(int k = i, d = j; k < j; k ++, d --) { int t = matrix[i][k]; matrix[i][k] = matrix[d][i]; matrix[d][i] = matrix[j][d]; matrix[j][d] = matrix[k][j]; matrix[k][j] = t; } } }}
20 / 20 test cases passed.Status: AcceptedRuntime: 332 ms
0 0
- [leetcode 48] Rotate Image
- 48、Rotate Image
- [LeetCode 48]Rotate Image
- leetcode || 48、Rotate Image
- leetcode-48 Rotate Image
- Rotate Image - LeetCode 48
- Leetcode 48: Rotate Image
- Leetcode #48 Rotate Image
- LeetCode(48) Rotate Image
- leetcode 48: Rotate Image
- 48Rotate Image
- Leetcode#48||Rotate Image
- [48]Rotate Image
- leetcode 48:Rotate Image
- 【leetcode】【48】Rotate Image
- LeetCode_OJ【48】Rotate Image
- Leetcode 48 - Rotate Image
- LeetCode 48 - Rotate Image
- UIViewController
- 杭电2203亲和串
- java synchronized静态同步方法与非静态同步方法,同步语句块
- Climbing Stairs
- 使用纯的CSS绘制简易的图形
- 48Rotate Image
- css transition属性详解
- double型未初始化直接运算出现小错误
- matlab实现画散点图(一个x对应多个y)
- java笔记--关于线程同步(5种同步方式)
- 剑指offer刷题之java实现的从上往下打印二叉树
- 白话空间统计之五:空间关系的概念化(下)
- Java反射机制之方法反射的基本操作
- Spring MVC 直接返还HTML视图