Logo
TGCATALOG
Catalog Collections Blog
Java | LeetCode

Java | LeetCode

LeetCode tasks and solutions in Java.

No ratings
283
30.11.2026
283
30.11.2026
No ratings
283
30.11.2026
Safe redirect via bot
О канале

LeetCode tasks and solutions in Java.

Подписчиков —
Тематика Technology
Ссылка @easy_java_task

We also recommend

Kekaton AI | Voiceover and voice clone
Kekaton AI | Voiceover and voice clone
Bot

AI bot for text-to-speech and voice cloning in Telegram. Create audio using neural network quickly and easily.

Description

LeetCode task solutions in Java with emphasis on clean code and optimization. Topics: arrays, trees, graphs, dynamic programming. Ideal for technical preparation.

Latest posts

Java | LeetCode
Java | LeetCode
🔒Открыть пост
и посмотреть медиа
Задача: 1203. Sort Items by Groups Respecting Dependencies Сложность: hard Есть n предметов, каждый из которых принадлежит нулевой или одной из m групп, где group[i] — это группа, к которой принадлежит i-й предмет, и равно -1, если i-й предмет не принадлежит никакой группе. Предметы и группы имеют индексацию с нуля. Группа может не иметь ни одного предмета. Верните отсортированный список предметов таким образом: Предметы, принадлежащие одной группе, расположены рядом друг с другом в отсортированном списке. Существуют некоторые отношения между этими предметами, где beforeItems[i] — это список, содержащий все предметы, которые должны быть перед i-м предметом в отсортированном массиве (слева от i-го предмета). Верните любое решение, если существует более одного решения, и верните пустой список, если решения не существует. Пример: Input: n = 8, m = 2, group = [-1,-1,1,0,0,1,0,-1], beforeItems = [[],[6],[5],[6],[3,6],[],[],[]] Output: [6,3,4,1,5,2,0,7] 👨💻 Алгоритм: 1⃣Инициализация и создание графов: Присвоить уникальные идентификаторы группам для элементов без группы. Создать два графа: item_graph для элементов и group_graph для групп. Также создать два массива для учета входящих рёбер для элементов и групп. 2⃣Построение графов: Пройти по массиву beforeItems и добавить зависимости между элементами в item_graph, увеличивая счётчик входящих рёбер. Если элементы принадлежат разным группам, добавить зависимость между группами в group_graph, увеличивая счётчик входящих рёбер. 3⃣Топологическая сортировка и создание итогового списка: Выполнить топологическую сортировку для элементов и групп. Если есть цикл, вернуть пустой список. Создать итоговый список, добавляя отсортированные элементы каждой группы. 😎 Решение: class Solution { public int[] sortItems(int n, int m, int[] group, List • > beforeItems) { int groupId = m; for (int i = 0; i < n; i++) if (group[i] == -1) group[i] = groupId++; Map itemGraph = new HashMap(); Map groupGraph = new HashMap(); int[] itemIndegree = new int[n], groupIndegree = new int[groupId]; for (int i = 0; i < n; i++) itemGraph.put(i, new ArrayList()); for (int i = 0; i < groupId; i++) groupGraph.put(i, new ArrayList()); for (int curr = 0; curr < n; curr++) { for (int prev : beforeItems.get(curr)) { itemGraph.get(prev).add(curr); itemIndegree[curr]++; if (group[curr] != group[prev]) { groupGraph.get(group[prev]).add(group[curr]); groupIndegree[group[curr]]++; } } } List itemOrder = topologicalSort(itemGraph, itemIndegree); List groupOrder = topologicalSort(groupGraph, groupIndegree); if (itemOrder.isEmpty() || groupOrder.isEmpty()) return new int[0]; Map orderedGroups = new HashMap(); for (int item : itemOrder) orderedGroups.computeIfAbsent(group[item], k -> new ArrayList()).add(item); List answerList = new ArrayList(); for (int groupIndex : groupOrder) answerList.addAll(orderedGroups.getOrDefault(groupIndex, new ArrayList())); return answerList.stream().mapToInt(Integer::intValue).toArray(); } private List topologicalSort(Map graph, int[] indegree) { List visited = new ArrayList(); Stack stack = new Stack(); for (int key : graph.keySet()) if (indegree[key] == 0) stack.add(key); while (!stack.isEmpty()) { int curr = stack.pop(); visited.add(curr); for (int next : graph.get(curr)) if (--indegree[next] == 0) stack.add(next); } return visited.size() == graph.size() ? visited : new ArrayList(); } } Ставь 👍 и забирай 📚 Базу знаний
Java | LeetCode
FAQ

Open Java | LeetCode in Telegram and press the Start button. No separate registration is required.

Yes. The service is designed to be straightforward: open the resource, follow the on-screen instructions and start using it.

No. You can use Java | LeetCode directly in Telegram unless the resource description says otherwise.

Access depends on the resource. Check the current information in Telegram after opening Java | LeetCode.

The exact features depend on the resource. Open Java | LeetCode to see its current functions, content and access conditions.

Reviews for channel Java | LeetCode

Log in to leave a review

Only registered users can share their opinion.

No reviews yet

Be the first to share your impression of this resource!

Similar resources

Loading
Switch to Light Theme
Home Catalog Collections Blog Login