diagonal_traverse_ii
1from collections import defaultdict 2from itertools import chain 3 4 5# @leet start 6class Solution: 7 def findDiagonalOrder(self, nums: list[list[int]]) -> list[int]: 8 """ 9 This question asks us to find the diagonal traverse of a list of lists, 10 where the lists could be jagged (i.e. are not a matrix) and the traversal 11 is just down to up. 12 13 This is pretty similar to Diagonal Traverse I, where the rows are grouped by 14 the sum of their y and x coordinates, and then reversed. 15 We do that and flatten the end list to get the final answer. 16 """ 17 18 m = len(nums) 19 rows = defaultdict(list) 20 21 for y in range(m): 22 for x, num in enumerate(nums[y]): 23 rows[y + x].append(num) 24 25 for v in rows.values(): 26 v.reverse() 27 28 return list(chain(*rows.values())) 29 30 31# @leet end 32 33 34def test(): 35 assert 2 + 2 == 4
class
Solution:
7class Solution: 8 def findDiagonalOrder(self, nums: list[list[int]]) -> list[int]: 9 """ 10 This question asks us to find the diagonal traverse of a list of lists, 11 where the lists could be jagged (i.e. are not a matrix) and the traversal 12 is just down to up. 13 14 This is pretty similar to Diagonal Traverse I, where the rows are grouped by 15 the sum of their y and x coordinates, and then reversed. 16 We do that and flatten the end list to get the final answer. 17 """ 18 19 m = len(nums) 20 rows = defaultdict(list) 21 22 for y in range(m): 23 for x, num in enumerate(nums[y]): 24 rows[y + x].append(num) 25 26 for v in rows.values(): 27 v.reverse() 28 29 return list(chain(*rows.values()))
def
findDiagonalOrder(self, nums: list[list[int]]) -> list[int]:
8 def findDiagonalOrder(self, nums: list[list[int]]) -> list[int]: 9 """ 10 This question asks us to find the diagonal traverse of a list of lists, 11 where the lists could be jagged (i.e. are not a matrix) and the traversal 12 is just down to up. 13 14 This is pretty similar to Diagonal Traverse I, where the rows are grouped by 15 the sum of their y and x coordinates, and then reversed. 16 We do that and flatten the end list to get the final answer. 17 """ 18 19 m = len(nums) 20 rows = defaultdict(list) 21 22 for y in range(m): 23 for x, num in enumerate(nums[y]): 24 rows[y + x].append(num) 25 26 for v in rows.values(): 27 v.reverse() 28 29 return list(chain(*rows.values()))
This question asks us to find the diagonal traverse of a list of lists, where the lists could be jagged (i.e. are not a matrix) and the traversal is just down to up.
This is pretty similar to Diagonal Traverse I, where the rows are grouped by the sum of their y and x coordinates, and then reversed. We do that and flatten the end list to get the final answer.
def
test():