day70(1.29)——leetcode面试经典150

210. 课程表 II

210. 课程表Ⅱ

这题跟之前那题一样!!!

题目:

题解:

java 复制代码
class Solution {
    public int[] findOrder(int numCourses, int[][] prerequisites) {
        //创建记录先修课程
        int[] pres = new int[numCourses];
        //创建映射表
        Map<Integer, List<Integer>> map = new HashMap<>();
        //进行初始化映射表
        for(int i=0;i<numCourses;i++) {
            map.put(i, new ArrayList<Integer>());
        }
        //根据prerequesties更新对应的pres,map
        for(int i=0;i<prerequisites.length;i++) {
            int course = prerequisites[i][0];
            int preCourse = prerequisites[i][1];
            map.get(preCourse).add(course);
            pres[course]++;
        }
        List<Integer> res = new ArrayList<>();
        int r = 0;
        //进行bfs遍历
        Queue<Integer> queue = new LinkedList<>();
        for(int i=0;i<numCourses;i++) {
            //如果没有先修课程
            if(pres[i]==0) {
                queue.offer(i);
            }
        }
        while(queue.size()>0) {
            int t = queue.poll();
            res.add(t);
            List<Integer> list = map.get(t);
            for(int l:list) {
                pres[l]--;
                if(pres[l]==0) {
                    queue.offer(l);
                }
            }
        }
        if(res.size()!=numCourses) {
            return new int[0];
        }
        return res.stream().mapToInt(i->i).toArray();
    }
}
相关推荐
hpoenixf5 小时前
2026 年前端面试问什么
前端·面试
Liu628886 小时前
C++中的工厂模式高级应用
开发语言·c++·算法
AI科技星6 小时前
全尺度角速度统一:基于 v ≡ c 的纯推导与验证
c语言·开发语言·人工智能·opencv·算法·机器学习·数据挖掘
参.商.6 小时前
【Day41】143. 重排链表
leetcode·golang
条tiao条7 小时前
KMP 算法详解:告别暴力匹配,让字符串匹配 “永不回头”
开发语言·算法
干啥啥不行,秃头第一名7 小时前
C++20概念(Concepts)入门指南
开发语言·c++·算法
RainyJiang7 小时前
谱写Kotlin协程面试进行曲-进阶篇(第二乐章)
面试·kotlin·android jetpack
zzh940777 小时前
Gemini 3.1 Pro 硬核推理优化剖析:思维织锦、动态计算与国内实测
算法
2301_807367197 小时前
C++中的解释器模式变体
开发语言·c++·算法
愣头不青8 小时前
617.合并二叉树
java·算法