All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g1401_1500.s1424_diagonal_traverse_ii.Solution Maven / Gradle / Ivy

There is a newer version: 1.38
Show newest version
package g1401_1500.s1424_diagonal_traverse_ii;

// #Medium #Array #Sorting #Heap_Priority_Queue
// #2022_03_28_Time_39_ms_(85.56%)_Space_109.5_MB_(78.06%)

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;

/**
 * 1424 - Diagonal Traverse II\.
 *
 * Medium
 *
 * Given a 2D integer array `nums`, return _all elements of_ `nums` _in diagonal order as shown in the below images_.
 *
 * **Example 1:**
 *
 * ![](https://assets.leetcode.com/uploads/2020/04/08/sample_1_1784.png)
 *
 * **Input:** nums = \[\[1,2,3],[4,5,6],[7,8,9]]
 *
 * **Output:** [1,4,2,7,5,3,8,6,9]
 *
 * **Example 2:**
 *
 * ![](https://assets.leetcode.com/uploads/2020/04/08/sample_2_1784.png)
 *
 * **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
**/
public class Solution {
    public int[] findDiagonalOrder(List> nums) {
        List ans = new ArrayList<>();
        ArrayDeque> queue = new ArrayDeque<>();
        int pos = 0;
        do {
            if (pos < nums.size()) {
                queue.offerFirst(nums.get(pos).iterator());
            }
            int sz = queue.size();
            while (--sz >= 0) {
                Iterator cur = queue.poll();
                ans.add(Objects.requireNonNull(cur).next());
                if (cur.hasNext()) {
                    queue.offer(cur);
                }
            }
            pos++;
        } while (!queue.isEmpty() || pos < nums.size());
        return ans.stream().mapToInt(o -> o).toArray();
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy