首页 > 试题广场 >

顺时针旋转矩阵(二)

[编程题]顺时针旋转矩阵(二)
  • 热度指数:344 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解

有一个nxn整数矩阵,请编写一个算法,将矩阵原地顺时针旋转90度。

给定一个nxn的矩阵,和矩阵的阶数n,请原地旋转矩阵。

数据范围:,矩阵中的值满足

要求:空间复杂度 ,时间复杂度

示例1

输入

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

输出

[[7,4,1],[8,5,2],[9,6,3]]
# -*- coding: utf-8 -*-


#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param mat int整型二维数组
# @param n int整型
# @return void
#
class Solution:
    """
    题目:
        https://www.nowcoder.com/practice/5b7029aae0f84935b3ac9fad9e33a246?tpId=196&tqId=40549&rp=1&ru=/exam/oj&qru=/exam/oj&sourceUrl=%2Fexam%2Foj%3FjudgeStatus%3D3%26page%3D1%26pageSize%3D50%26search%3D%26tab%3D%25E7%25AE%2597%25E6%25B3%2595%25E7%25AF%2587%26topicId%3D196&difficulty=undefined&judgeStatus=3&tags=&title=
    算法:
        顺时针旋转90° ==> 1. 按主对角线翻转 2. 按行翻转
    复杂度:
        时间复杂度:O(mn)
        空间复杂度:O(1)
    """

    def rotateMatrix(self, mat, n):
        # write code here
        for i in range(1, n):
            for j in range(i):
                mat[i][j], mat[j][i] = mat[j][i], mat[i][j]

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

        return mat


if __name__ == "__main__":
    sol = Solution()

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

    res = sol.rotateMatrix(matrix, n)

    print res

发表于 2022-06-26 21:56:37 回复(0)