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();
    }
}
相关推荐
JAVA面经实录9179 小时前
Java 数据结构与算法 (终极完整学习文档)
java·数据结构·算法
JAVA面经实录9179 小时前
操作系统面试题
java·服务器·数据库·计算机网络·面试
AI人工智能+电脑小能手10 小时前
【大白话说Java面试题 第117题】【并发篇】第17题:线程有几种状态,之间如何转换?
java·开发语言·面试
开源Z10 小时前
LeetCode 42 · 接雨水:从暴力到双指针的三步优化
算法·leetcode
旖-旎10 小时前
《LeetCode 695 岛屿的最大面积 FloodFill DFS 解法》
c++·算法·力扣·深度优先遍历·floodfill
syagain_zsx11 小时前
STL 之 vector 讲练结合
c++·算法
牛油果子哥q12 小时前
STL set与map底层精讲,红黑树适配原理、有序去重特性、迭代器遍历、API实战与面试核心考点全解
开发语言·数据结构·c++·面试
MartinYeung512 小时前
[论文学习]DP2Unlearning:高效且具保证的大型语言模型遗忘框架(基于差分隐私的 LLM Unlearning 方法)
学习·算法·语言模型
yoothey13 小时前
MySQL事务机制解析 - 面试高分知识点
数据库·mysql·面试