TGViewer
JavaScript | LeetCode JavaScript | LeetCode @easy_frontend_task · 8.3K subscribers
Post #1632 831
Задача: 1424. Diagonal Traverse II
Сложность: medium

Дан двумерный целочисленный массив nums, верните все элементы nums в диагональном порядке.

Пример:
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]


👨‍💻 Алгоритм:

1⃣Инициализируйте очередь с (0, 0) и список ответов ans.

2⃣Пока очередь не пуста:
Извлеките (row, col) из очереди.
Добавьте nums[row][col] в ans.
Если col == 0 и row + 1 в пределах массива, добавьте (row + 1, col) в очередь.
Если col + 1 в пределах текущей строки, добавьте (row, col + 1) в очередь.

3⃣Верните ans.

😎 Решение:
class Solution {
findDiagonalOrder(nums) {
const queue = [[0, 0]];
const ans = [];

while (queue.length > 0) {
const [row, col] = queue.shift();
ans.push(nums[row][col]);

if (col === 0 && row + 1 < nums.length) {
queue.push([row + 1, col]);
}

if (col + 1 < nums[row].length) {
queue.push([row, col + 1]);
}
}

return ans;
}
}


Ставь 👍 и забирай 📚 Базу знаний
More from @easy_frontend_task
  1. Oct 17, 2026Сложность: medium Задача: 275. H-Index II Дан массив целых чисел citations, где citations[…
  2. Oct 13, 2026Задача: 687. Longest Univalue Path Сложность: medium Дано корень бинарного дерева, верните…
  3. Oct 11, 2026Задача: 651. 4 Keys Keyboard Сложность: medium Представьте, что у вас есть специальная кла…
  4. Oct 9, 2026Задача: 1054. Distant Barcodes Сложность: medium На складе имеется ряд штрих-кодов, где i-…
  5. Oct 9, 2026Задача: 1237. Find Positive Integer Solution for a Given Equation Сложность: medium Если д…
  6. Oct 8, 2026Задача: №19. Remove Nth Node From End of List Сложность: medium Дан связанный список и чис…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →