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 innums
.
思路:发现所有往上走的元素,index (i + j ) 都等于一个数, 0,1,2,3,4
那么就用hashmap<Integer, List<Integer>> 来收集,因为是从下往上搜集,那么for loop都是从最后一行往上走;算出maxkey和所有元素的个数,就按照hashmap的list进行输出即可;
class Solution {
public int[] findDiagonalOrder(List<List<Integer>> nums) {
HashMap<Integer, List<Integer>> hashmap = new HashMap<>();
int total = 0;
int maxkey = 0;
for(int i = nums.size() - 1; i >= 0; i--) {
List<Integer> list = nums.get(i);
for(int j = 0; j < list.size(); j++) {
hashmap.putIfAbsent(i + j, new ArrayList<Integer>());
hashmap.get(i + j).add(list.get(j));
maxkey = Math.max(maxkey, i + j);
total++;
}
}
int[] res = new int[total];
int index = 0;
for(int i = 0; i <= maxkey; i++) {
for(Integer integer: hashmap.get(i)) {
res[index++] = integer;
}
}
return res;
}
}