
| import java.util.ArrayList; |
| import java.util.Deque; |
| |
| class Solution { |
| public int[] findOrder(int numCourses, int[][] prerequisites) { |
| |
| |
| |
| |
| int[] cnt = new int[numCourses]; |
| |
| |
| ArrayList<ArrayList<Integer>> graph = new ArrayList<>(); |
| |
| for (int i = 0; i < cnt.length; i++) { |
| graph.add(new ArrayList<Integer>()); |
| } |
| for (int i = 0; i < prerequisites.length; i++) { |
| int from = prerequisites[i][1]; |
| int to = prerequisites[i][0]; |
| graph.get(from).add(to); |
| cnt[to]++; |
| } |
| |
| int[] queue = new int[numCourses]; |
| int l = 0; |
| int r = 0; |
| |
| |
| for (int i = 0; i < numCourses; i++) { |
| if (cnt[i] == 0) { |
| queue[r++] = i; |
| } |
| } |
| int[] ans = new int[numCourses]; |
| int a = 0; |
| |
| while (l != r) { |
| int cur = queue[l++]; |
| ans[a++] = cur; |
| for (int next : graph.get(cur)) { |
| cnt[next]--; |
| if (cnt[next] == 0) { |
| |
| queue[r++] = next; |
| } |
| } |
| |
| } |
| if (a == numCourses) { |
| return ans; |
| } |
| return new int[] {}; |
| } |
| } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统