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