LeetCode 1424. Diagonal Traverse II

原题链接在这里:https://leetcode.com/problems/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

题解:

In the matrix, when index sum i + j is equal, then elements with equal sum index are on the same printing line.

Have a map to maintain the index sum and its elements.
Print from small to large index sum, for each list, print from the end.

Time Complexity: O(m * n). m = nums.size(). n is average length of list in the nums.

Space: O(m * n).

AC Java:

 1 class Solution {
 2     public int[] findDiagonalOrder(List<List<Integer>> nums) {
 3         int count = 0;
 4         int maxKey = 0;
 5         HashMap<Integer, ArrayList<Integer>> hm = new HashMap<>();
 6         for(int i = 0; i < nums.size(); i++){
 7             for(int j = 0; j < nums.get(i).size(); j++){
 8                 int sum = i + j;
 9                 hm.computeIfAbsent(sum, k -> new ArrayList<Integer>()).add(nums.get(i).get(j));
10                 count++;
11                 maxKey = Math.max(maxKey, sum);
12             }
13         }
14 
15         int[] res = new int[count];
16         int ind = 0;
17         for(int i = 0; i <= maxKey; i++){
18             if(hm.containsKey(i)){
19                 List<Integer> ls = hm.get(i);
20                 for(int j = ls.size() - 1; j >=0; j--){
21                     res[ind++] = ls.get(j);
22                 }
23             }
24         }
25 
26         return res;
27     }
28 }

类似Diagonal Traverse.

posted @ 2024-04-21 10:04  Dylan_Java_NYC  阅读(4)  评论(0编辑  收藏  举报