Diagonal Traverse II

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 in nums.

思路:发现所有往上走的元素,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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值