当前位置: 首页 > article >正文

【hot100】刷题记录(10)-旋转图像

题目描述:

给定一个 × n 的二维矩阵 matrix 表示一个图像。请你将图像顺时针旋转 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]]

提示:

  • n == matrix.length == matrix[i].length
  • 1 <= n <= 20
  • -1000 <= matrix[i][j] <= 1000

我的作答:

思路就是矩阵求转置(图中逆是转置)后再按列翻转180°,就可以实现按顺时针翻转90°

class Solution(object):
    def rotate(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: None Do not return anything, modify matrix in-place instead.
        """
        if not matrix: return []
        for i in range(len(matrix)):
            for j in range(i):
                temp = matrix[i][j] #类似于矩阵求逆
                matrix[i][j] = matrix[j][i]
                matrix[j][i] = temp
        for row in range(len(matrix)):
            matrix[row][:] = reversed(matrix[row][:]) #每一行翻转180°
        return matrix

参考:

类似于如下图的方式:

class Solution(object):
    def rotate(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: None Do not return anything, modify matrix in-place instead.
        """
        pos1,pos2 = 0,len(matrix)-1
        while   pos1<pos2:
            add = 0
            while   add < pos2-pos1:
                #左上角为0块,右上角为1块,右下角为2块,左下角为3块
                temp = matrix[pos2-add][pos1]
                matrix[pos2-add][pos1] = matrix[pos2][pos2-add]
                #3 = 2
                matrix[pos2][pos2-add] = matrix[pos1+add][pos2]
                #2 = 1
                matrix[pos1+add][pos2] = matrix[pos1][pos1+add]
                #1 = 0
                matrix[pos1][pos1+add] = temp
                #0 = temp
                add = add+1
            pos1 = pos1+1
            pos2 = pos2-1


http://www.kler.cn/a/530623.html

相关文章:

  • Java:日期时间范围的处理
  • PyCharm中使用Ollama安装和应用Deepseek R1模型:完整指南
  • 洛谷 P10289 [GESP样题 八级] 小杨的旅游 C++ 完整题解
  • Spring Boot 实例解析:配置文件
  • 玩转Docker | 使用Docker部署SSCMS内容管理系统
  • 如何用微信小程序写春联
  • MVS pythonSamples 运行环境配置
  • 应用层协议——HTTP协议
  • CharacterEncoder类
  • Linux环境下的Java项目部署技巧:安装 Mysql
  • 每日一题——包含min函数的栈
  • pandas(二)读取数据
  • 【Springboot2】多环境开发简单教程
  • Spark On Yarn External Shuffle Service
  • 17.[前端开发]Day17-形变-动画-vertical-align
  • 【高等数学】贝塞尔函数
  • 构建一个研发助手Agent:提升开发效率的实践
  • ArrayBlockingQueue源码分析
  • Codeforces Round 863 (Div. 3) E. Living Sequence
  • Android --- handler详解
  • Kanass基础教程-创建项目
  • 【tiktok 国际版抖抖♬♬ __ac_signature算法】逆向分析
  • 11.kafka开启jmx
  • LeetCode 0598.区间加法 II:最小值
  • 洛谷 P5146 最大差值 C语言
  • 力扣第435场周赛讲解