【Leetcode】旋转矩阵

题目链接:https://leetcode.cn/problems/rotate-matrix-lcci/description/

题目描述

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

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

示例

思路一

先转置再逆序

代码

python 复制代码
class Solution:
    def rotate(self, matrix: List[List[int]]) -> None:
        row, col = len(matrix), len(matrix[0])
        for i in range(row):
            for j in range(i, col):
                tmp = matrix[i][j]
                matrix[i][j] = matrix[j][i]
                matrix[j][i] = tmp
        
        for i in range(row):
            matrix[i] = matrix[i][::-1]

思路2

代码

python 复制代码
class Solution:
    def rotate(self, matrix: List[List[int]]) -> None:
        n = len(matrix)
        for i in range(n // 2):
            for j in range((n+1) // 2):
                matrix[i][j], matrix[n - j - 1][i], matrix[n - i - 1][n - j - 1], matrix[j][n - i - 1] \
                    = matrix[n - j - 1][i], matrix[n - i - 1][n - j - 1], matrix[j][n - i - 1], matrix[i][j]
相关推荐
2401_8414956410 小时前
【LeetCode刷题】轮转数组
数据结构·python·算法·leetcode·数组·双指针·轮转数组
Aspect of twilight11 小时前
LeetCode华为2025年秋招AI大模型岗刷题(四)
算法·leetcode·职场和发展
有泽改之_18 小时前
leetcode146、OrderedDict与lru_cache
python·leetcode·链表
im_AMBER18 小时前
Leetcode 74 K 和数对的最大数目
数据结构·笔记·学习·算法·leetcode
t1987512818 小时前
电力系统经典节点系统潮流计算MATLAB实现
人工智能·算法·matlab
断剑zou天涯18 小时前
【算法笔记】蓄水池算法
笔记·算法
长安er18 小时前
LeetCode 206/92/25 链表翻转问题-“盒子-标签-纸条模型”
java·数据结构·算法·leetcode·链表·链表翻转
Benmao⁢18 小时前
C语言期末复习笔记
c语言·开发语言·笔记·leetcode·面试·蓝桥杯
唯道行19 小时前
计算机图形学·23 Weiler-Athenton多边形裁剪算法
算法·计算机视觉·几何学·计算机图形学·opengl
CoderYanger19 小时前
动态规划算法-01背包问题:50.分割等和子集
java·算法·leetcode·动态规划·1024程序员节