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
原创粉丝点击