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();
    }
}
相关推荐
致Great1 小时前
DeepSeek Harness插件开发实战教程:我让它自己写了一个 arXiv 搜索插件
算法
ShineWinsu2 小时前
对于C++:auto_ptr、unique_ptr、shared_ptr的模拟实现
c++·面试·笔试·智能指针·unique_ptr·shared_ptr·auto_ptr
黄敬峰5 小时前
一文搞懂 NestJS 后端框架:工厂模式、模块化与装饰器
面试
罗西的思考6 小时前
【Agent OS / AIOS】AOHP 深度解读:当 OS 开始为 Agent 而设计
人工智能·算法·机器学习
民乐团扒谱机6 小时前
【微实验】组合优化matlab实战(马科维茨投资模型):在收益与风险之间,寻找最优的人生配比
大数据·人工智能·算法·机器学习·数学建模·matlab·组合优化
码匠许师傅6 小时前
【C++ 面试真题】聊聊 C++ 的多继承与虚继承
开发语言·c++·面试
kyriewen7 小时前
面试官说"打开你的AI工具"——我才发现,他考的根本不是写代码
前端·人工智能·面试
Nil2087 小时前
leetcode 160相交链表
算法·leetcode·链表
迷途之人不知返8 小时前
算法系列2:滑动窗口
算法
Herbert_hwt8 小时前
C语言零基础入门:循环控制与数据类型详解
c语言·数据结构·算法