LeetCode 1424. Diagonal Traverse II Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
1424. Diagonal Traverse II

Description

Given a 2D integer array 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]

 

Constraints:

  • 1 <= nums.length <= 105
  • 1 <= nums[i].length <= 105
  • 1 <= sum(nums[i].length) <= 105
  • 1 <= nums[i][j] <= 105

Solutions

Solution 1: Sorting

We observe that:

  • The value of i + j is the same for each diagonal;
  • The value of i + j for the next diagonal is greater than that of the previous diagonal;
  • Within the same diagonal, the value of i + j is the same, and the value of j increases from small to large.

Therefore, we store all numbers in the form of (i, j, nums[i][j]) into arr, and then sort according to the first two items. Finally, return the array composed of the values at index 2 of all elements in arr.

The time complexity is O(n × log n), where n is the number of elements in the array nums. The space complexity is O(n).

PythonJavaC++GoTypeScriptC#
class Solution: def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]: arr = [] for i, row in enumerate(nums): for j, v in enumerate(row): arr.append((i + j, j, v)) arr.sort() return [v[2] for v in arr](code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !