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();
    }
}
相关推荐
lisw054 小时前
稀疏算法概述!
算法·机器人·无人机
思想觉悟5 小时前
Aosp实战之自定义开机启动进程
c++·面试
YLCHUP5 小时前
【括号匹配+dp优化】题解:双端括号(brackets)_动态规划_状态优化_数学建模_贪心_性质挖掘_STLmap_C++算法竞赛
数据结构·c++·笔记·算法·数学建模·贪心算法·动态规划
郝学胜-神的一滴6 小时前
Effective STL 条款09:慎重选择删除元素的方法
开发语言·网络·数据结构·c++·算法·stl
geovindu10 小时前
python:Logistic Regression
开发语言·后端·python·算法
geovindu12 小时前
python: Random Forest
开发语言·后端·python·算法·随机森林
凌冰_13 小时前
数据结构 - 线性结构(三)
java·数据结构·算法·软件工程
拂拉氏13 小时前
【知识讲解】 数据结构与算法-树状数组的认识
数据结构·算法·树状数组
ShineWinsu14 小时前
对于Qt:事件分发器以及事件过滤器的解析
c++·qt·面试·gui·客户端·事件过滤器·事件分发器
饮水桶_T15 小时前
C++ STL00 | 六大核心组件协作框架 笔记
开发语言·算法·百度·facebook·新浪微博