zoukankan      html  css  js  c++  java
  • 498. 对角线遍历

    给定一个含有 M x N 个元素的矩阵(M 行,N 列),请以对角线遍历的顺序返回这个矩阵中的所有元素,对角线遍历如下图所示。
    示例:

    • 输入:

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

    • 输出:

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

    • 解释:

    • 说明:

    给定矩阵中的元素总数不会超过 100000 。

    • 分析:

    仔细观察输出的结果,发现对角线上的值,在二维数组中对应的 row+line 值都是相同的,故通过该规律得到一个按遍历顺序输出的 list,接着需要将 list中为奇数的值所在的line,按倒序输出结果,即可得到按对角线输出的结果

    • 解法:
    
    class Solution(object):
        def findDiagonalOrder(self, matrix):
            """
            :type matrix: List[List[int]]
            :rtype: List[int]
            """
    		res = []
            lines = collections.defaultdict(list)
            for row in range(len(matrix)):
                for line in range(len(matrix[0])):
                    lines[row+line].append(matrix[row][line])
            for key, value in lines.items():
                if key % 2 == 0:
                    res += value[::-1]
                else:
                    res += value
            return res
    
  • 相关阅读:
    封装( 增删改 查 )类
    php注释规范
    php访问mysql数据库
    php 文件限速下载代码
    jQuery鼠标事件汇总
    权限管理
    文件管理 打开-返回上级
    文件操作
    简单的文件上传
    ajax XML
  • 原文地址:https://www.cnblogs.com/AimeeCodeWorld/p/10806033.html
Copyright © 2011-2022 走看看