LeetCode 48 Rotate Image 解题思路和python代码

题目:

You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).

You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

Example 1:

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]

Output: [[7,4,1],[8,5,2],[9,6,3]]

Example 2:

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

Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]

Constraints:

n == matrix.length == matrix[i].length

1 <= n <= 20

-1000 <= matrix[i][j] <= 1000

解题思路:

首先,转置这个matrix。

bash 复制代码
[[1, 2, 3],
 [4, 5, 6],
 [7, 8, 9]]

转置后变成:

bash 复制代码
[[1, 4, 7],
 [2, 5, 8],
 [3, 6, 9]]

接着,把 matrix 中的每一行都reverse。

bash 复制代码
[[7, 4, 1],
 [8, 5, 2],
 [9, 6, 3]]

完成将 matrix 旋转90°。

转置矩阵的 time complexity 是O(n^2),

reverse矩阵中每一行的 time complexity 也是 O(n^2)。

整体的 time complexity 是O(n^2)。

space complexity 是 O(1)。

python 复制代码
class Solution:
    def rotate(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """
        n = len(matrix)

        for i in range(n):
            for j in range(i, n):
                matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]

        for i in range(n):
            matrix[i].reverse()

        return matrix
相关推荐
魔尔助理顾问1 小时前
Flask如何读取配置信息
python·flask·bootstrap
康谋自动驾驶1 小时前
康谋分享 | 自动驾驶仿真进入“标准时代”:aiSim全面对接ASAM OpenX
人工智能·科技·算法·机器学习·自动驾驶·汽车
C++ 老炮儿的技术栈2 小时前
什么是函数重载?为什么 C 不支持函数重载,而 C++能支持函数重载?
c语言·开发语言·c++·qt·算法
jc_hook2 小时前
Python 接入DeepSeek
python·大模型·deepseek
chicpopoo2 小时前
Python打卡DAY25
开发语言·python
yychen_java2 小时前
R-tree详解
java·算法·r-tree
MarkHard1233 小时前
Leetcode (力扣)做题记录 hot100(62,64,287,108)
算法·leetcode·职场和发展
crazyme_63 小时前
深入掌握 Python 切片操作:解锁数据处理的高效密码
开发语言·python
一只鱼^_3 小时前
牛客练习赛138(首篇万字题解???)
数据结构·c++·算法·贪心算法·动态规划·广度优先·图搜索算法
一只码代码的章鱼3 小时前
Spring的 @Validate注解详细分析
前端·spring boot·算法