Leetcode: 面试题 01.07. 旋转矩阵

耗尽温柔 提交于 2020-04-09 04:51:34

题目

链接:https://leetcode-cn.com/problems/rotate-matrix-lcci

给你一幅由 N × N 矩阵表示的图像,其中每个像素的大小为 4 字节。请你设计一种算法,将图像旋转 90 度。

不占用额外内存空间能否做到?

示例 1:

给定 matrix = 
[
  [1,2,3],
  [4,5,6],
  [7,8,9]
],

原地旋转输入矩阵,使其变为:
[
  [7,4,1],
  [8,5,2],
  [9,6,3]
]
示例 2:

给定 matrix =
[
  [ 5, 1, 9,11],
  [ 2, 4, 8,10],
  [13, 3, 6, 7],
  [15,14,12,16]
], 

原地旋转输入矩阵,使其变为:
[
  [15,13, 2, 5],
  [14, 3, 4, 1],
  [12, 6, 8, 9],
  [16, 7,10,11]
]

解题记录

方法1

先水平翻转,在根据对角线翻转,两次翻转获得旋转 90 度的效果,这里翻转也可选择垂直翻转,对角翻转的对角线不同:

class Solution {
    public static void rotate(int[][] matrix) {
        int maxN = matrix.length;

        for (int i=0; i<(maxN/2); i++) {
            swap(matrix, i, maxN-1-i);
        }

        for(int y=0; y<maxN-1; y++){
            for (int x=maxN-1; x>y; x--){
                deepSwap(matrix, x, y);
            }
        }
    }

    public static void swap(int[][] matrix, int y1, int y2){
        int[] tmp = matrix[y1];
        matrix[y1] = matrix[y2];
        matrix[y2] = tmp;
    }

    public static void deepSwap(int[][] matrix, int x, int y){
        int tmp = matrix[x][y];
        matrix[x][y] = matrix[y][x];
        matrix[y][x] = tmp;
    }
}

结果

在这里插入图片描述

方法2

直接旋转换位,每次更换四个位置的数值。
在这里插入图片描述

class Solution {
    public static void rotate(int[][] matrix) {
        int n = matrix.length;
        for(int y=0; y<n/2; y++){
            for (int x=0; x<(n+1)/2; x++){
                deepSwap(matrix, x, y,n-x-1, n-y-1);
            }
        }
    }

    public static void deepSwap(int[][] m, int a, int b, int c, int d){
        int tmp = m[a][b];
        m[a][b] = m[d][a];
        m[d][a] = m[c][d];
        m[c][d] = m[b][c];
        m[b][c] = tmp;
    }
}

进阶

使用python的numpy包可以简单实现对矩阵的操作:

直接旋转

import numpy as np
class Solution:
    def rotate(self, matrix: List[List[int]]) -> None:
        matrix[:]=np.rot90(matrix, -1).tolist()

两次翻转

import numpy as np
class Solution:
    def rotate(self, matrix: List[List[int]]) -> None:
        matrix[:] = np.flipud(matrix).T.tolist()

耗时

在这里插入图片描述

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!