zoukankan      html  css  js  c++  java
  • 54. 螺旋矩阵

    给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。

    • 示例 1:

    输入:
    [
    [ 1, 2, 3 ],
    [ 4, 5, 6 ],
    [ 7, 8, 9 ]
    ]
    输出: [1,2,3,6,9,8,7,4,5]

    • 示例 2:

    输入:
    [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9,10,11,12]
    ]
    输出: [1,2,3,4,8,12,11,10,9,5,6,7]

    • 分析:

    根据输出结果发现需要将二维数组的第一行结果按顺序插入列表,接着按照二维数组中行的顺序,插入每一行最后一个元素,接着获取到二维数组中最后一行的值倒序插入,最后将二维数组中剩余的元素按顺序插入列表即可

    • 解法:
    class Solution(object):
        def spiralOrder(self, matrix):
            """
            :type matrix: List[List[int]]
            :rtype: List[int]
            """
    		ret = []
            while matrix:
                ret += matrix.pop(0)
                if matrix and matrix[0]:
                    for row in matrix:
                        ret.append(row.pop())
                if matrix:
                    ret += matrix.pop()[::-1]
                if matrix and matrix[0]:
                    for row in matrix[::-1]:
                        ret.append(row.pop(0))
            return ret
    
  • 相关阅读:
    poj3253Fence Repair (Huffman)
    poi3617Best Cow Line ——贪心法
    高级排序之——归并排序
    Aizu
    初级排序——冒泡排序
    cookie会话
    加载web资源文件
    servlet
    Http

  • 原文地址:https://www.cnblogs.com/AimeeCodeWorld/p/10806253.html
Copyright © 2011-2022 走看看