給你一個列表 nums ,裏面每一個元素都是一個整數列表。請你依照下面各圖的規則,按順序返回 nums 中對角線上的整數。
示例 1:
輸入:nums = [[1,2,3],[4,5,6],[7,8,9]]
輸出:[1,4,2,7,5,3,8,6,9]
示例 2:
輸入:nums = [[1,2,3,4,5],[6,7],[8],[9,10,11],[12,13,14,15,16]]
輸出:[1,6,2,8,7,3,9,4,12,10,5,13,11,14,15,16]
示例 3:
輸入:nums = [[1,2,3],[4],[5,6,7],[8],[9,10,11]]
輸出:[1,4,2,5,3,8,6,9,7,10,11]
示例 4:
輸入:nums = [[1,2,3,4,5,6]]
輸出:[1,2,3,4,5,6]
提示:
1 <= nums.length <= 10^5
1 <= nums[i].length <= 10^5
1 <= nums[i][j] <= 10^9
nums 中最多有 10^5 個數字。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/diagonal-traverse-ii
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
class Solution {
public int[] findDiagonalOrder(List<List<Integer>> nums) {
int n = nums.size();
int m = 0;
int len = 0;
Map<Integer,List<Integer>> map = new TreeMap<>();
for(int i = n-1; i >= 0; i--){
List<Integer> tmp = nums.get(i);
len += tmp.size();
for(int j = 0; j < tmp.size(); j++){
if(!map.containsKey(i+j)) map.put(i+j, new LinkedList<Integer>());
map.get(i+j).add(nums.get(i).get(j));
}
}
int[] res = new int[len];
int count = 0;
for(Map.Entry<Integer, List<Integer>> entry: map.entrySet()){
for(int num:entry.getValue()){
res[count++] = num;
}
}
return res;
}
}