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();
    }
}
相关推荐
中微极客21 小时前
降维算法75倍加速:从PCA到稀疏字典学习的工程实践
人工智能·学习·算法
storyseek21 小时前
前缀和实现Kogge-Stone算法
数据结构·算法
元Y亨H1 天前
开发者必须掌握的十大核心算法
算法
元Y亨H1 天前
深度解构:数据结构与算法的理论基石与工程演进
数据结构·算法
元Y亨H1 天前
数据结构与算法的通俗指南
数据结构·算法
HeiSenBerg1 天前
Android Lifecycle 原理完整剖析:从监听、事件分发到状态驱动
面试
2301_764441331 天前
用动力学系统(微分方程)为 Kernberg 的客体关系单元提供数学化的操作定义,把“自体—客体“这对心理结构建模成一个二维耦合系统
数据结构·python·算法·数学建模
林泽毅1 天前
PyTRIO快速入门(二):Datum构建
人工智能·算法·产品
keep intensify1 天前
最长有效括号
算法·leetcode·动态规划
CoderYanger1 天前
A.每日一题:1979. 找出数组的最大公约数
java·程序人生·算法·leetcode·面试·职场和发展·学习方法