Diagonal Traverse II LeetCode solution in Java

1
class Solution {
2
public int[] findDiagonalOrder(List<List<Integer>> nums) {
3
HashMap<Integer, Stack<Integer>> map = new HashMap();
4

5
for (int i = 0; i < nums.size(); i++) {
6
for (int j = 0; j < nums.get(i).size(); j++) {
7
int z = i + j;
8
if (map.containsKey(z)) {
9
map.get(z).add(nums.get(i).get(j));
10
} else {
11
Stack<Integer> stk = new Stack<>();
12
stk.push(nums.get(i).get(j));
13
map.put(z, stk);
14
}
15
}
16
}
17
ArrayList<Integer> arr = new ArrayList<>();
18
int k = 0;
19
while (true) {
20
if (map.containsKey(k)) {
21
int size = map.get(k).size();
22
while (size-- > 0) {
23
arr.add(map.get(k).pop());
24
}
25
k++;
26
} else {
27
break;
28
}
29
}
30
int[] res = new int[arr.size()];
31
for (int i = 0; i < res.length; i++) {
32
res[i] = arr.get(i);
33
}
34

35
return res;
36
}
37
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0