[leetcode] 1424. Diagonal Traverse II

Description

Given a list of lists of integers, nums, return all elements of nums in diagonal order as shown in the below images.

Example 1:

Input: nums = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,4,2,7,5,3,8,6,9]

Example 2:

Input: nums = [[1,2,3,4,5],[6,7],[8],[9,10,11],[12,13,14,15,16]]
Output: [1,6,2,8,7,3,9,4,12,10,5,13,11,14,15,16]

Example 3:

Input: nums = [[1,2,3],[4],[5,6,7],[8],[9,10,11]]
Output: [1,4,2,5,3,8,6,9,7,10,11]

Example 4:

Input: nums = [[1,2,3,4,5,6]]
Output: [1,2,3,4,5,6]

Constraints:

  • 1 <= nums.length <= 10^5
  • 1 <= nums[i].length <= 10^5
  • 1 <= nums[i][j] <= 10^9
  • There at most 10^5 elements in nums.

分析

题目的意思是:给你一个数组,按照斜对角线输出,这次对角线是从左下到右上角,所以跟一般的不一样,我开始也没有什么好的思路,后面看了一下提示,发现按照这种对角线输出,同一斜线的坐标的和是一样的,所以可以把当前的矩阵变成一个元组,然后进行排序就能够得到结果了,元组的格式为(row_index+col_index,row_index,val),第一个值为当前值的坐标只和,第二个值是行索引,第三个是值,按照第一个值进行排序就能够得到坐标从小到大的列表,然后输出求一个逆序就能够得到结果了哈。

代码

class Solution:
    def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]:
        m=len(nums)
        list_data=[]
        for i in range(m):
            for j in range(len(nums[i])):
                list_data.append([i+j,i,nums[i][j]])
        arr=sorted(list_data,key=lambda x:x[0],reverse=True)
        res=[]
        for val in arr:
            res.append(val[2])
        res.reverse()
        return res
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值