zoukankan      html  css  js  c++  java
  • Leetcode练习(Python):数组类:第54题:给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。

    题目:
    给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
    思路:
    使用两个指针,然后控制好边界就可以了。
    程序:
    class Solution:
        def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
            row = len(matrix)
            if row <= 0:
                return []
            column = len(matrix[0])
            result = []

            row_begin = 0
            row_end = row - 1
            column_begin = 0
            column_end = column - 1

            while row_begin <= row_end and column_begin <= column_end:
                for index1 in range(column_begin, column_end + 1):
                    result.append(matrix[row_begin][index1])
                row_begin += 1
                
                for index2 in range(row_begin, row_end + 1):
                    result.append(matrix[index2][column_end])
                column_end -= 1

                for index1 in range(column_end, column_begin - 1, -1):
                    if row_end >= row_begin:
                        result.append(matrix[row_end][index1])
                row_end -= 1

                for index2 in range(row_end, row_begin - 1, -1):
                    if column_end >= column_begin:
                        result.append(matrix[index2][column_begin])
                column_begin += 1
            
            return result
  • 相关阅读:
    node 使用笔记
    体会 git 之优越性
    Notes for building gimp-print
    Selenium Books
    Using MongoDB in C#
    Learning coding online
    USING NHIBERNATE WITH MySQL
    Data Visualization Books
    Web Automation with Selenium (C#)
    Gearman In Action
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12737090.html
Copyright © 2011-2022 走看看