zoukankan      html  css  js  c++  java
  • [LeetCode]题解(python):048-Rotate Image


    题目来源


    https://leetcode.com/problems/rotate-image/

    You are given an n x n 2D matrix representing an image.

    Rotate the image by 90 degrees (clockwise).

    Follow up:
    Could you do this in-place?


    题意分析


    Input:a matrix represented with list[list[]]

    Output:a matrix 

    Conditions:rotate 90 degrees clockwise


    题目思路


    注意到是将原来的矩阵顺时针旋转90度,本来直接转换比较费劲,网上大神说先转置然后每一行reverse即得所求,仔细观察矩阵的构造,的确如此,代码就几行……注意观察,不一定要一步得出答案。


    AC代码(Python)


     1 _author_ = "YE"
     2 # -*- coding:utf-8 -*-
     3 
     4 class Solution(object):
     5     def rotate(self, matrix):
     6         """
     7         :type matrix: List[List[int]]
     8         :rtype: void Do not return anything, modify matrix in-place instead.
     9         """
    10         n = len(matrix)
    11         for i in range(n):
    12             for j in range(i + 1, n):
    13                 matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
    14 
    15         for i in range(n):
    16             matrix[i].reverse()
    17 
    18 s = Solution()
    19 f = [[1,2,3],
    20     [4,5,6],
    21     [7,8,9]]
    22 
    23 print(s.rotate(f))
    24 print(f)
  • 相关阅读:
    LeetCode:数组(三)
    LeetCode:数组(二)
    LeetCode:数组(一)
    python实现栈的基本操作
    python基本内置函数
    Pycharm的常见Debug调试方法(持续更新)
    计算广告系列(一)-基本概念整理
    es与solr对比
    数据库优化
    java线程池
  • 原文地址:https://www.cnblogs.com/loadofleaf/p/5052011.html
Copyright © 2011-2022 走看看