内卷大厂系列《课程表问题三连击》

1,018 阅读6分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第27天,点击查看活动详情

大厂高频算法面试题:《课程表问题系列》,您将学到什么是图?什么是有向图?什么是无相图?什么是图的拓扑序?通过图的拓扑序解决有依赖关系的场景。快来一起学习吧!

一、课程表问题 I

你这个学期必须选修 numCourses 门课程,记为 0 到 numCourses - 1 。

在选修某些课程之前需要一些先修课程。 先修课程按数组 prerequisites 给出,其中 prerequisites[i] = [ai, bi] ,表示如果要学习课程 ai 则 必须 先学习课程 bi 。

  • 例如,先修课程对 [0, 1] 表示:想要学习课程 0 ,你需要先完成课程 1 。

请你判断是否可能完成所有课程的学习?如果可以,返回 true ;否则,返回 false 。

示例 1

输入:numCourses = 2, prerequisites = [[1,0]]
输出:true
解释:总共有 2 门课程。学习课程 1 之前,你需要完成课程 0 。这是可能的。

示例 2

输入:numCourses = 2, prerequisites = [[1,0],[0,1]]
输出:false
解释:总共有 2 门课程。学习课程 1 之前,你需要先完成​课程 0 ;并且学习课程 0 之前,你还应先完成课程 1 。这是不可能的。

leetcode

1、分析

想修某门课程,先把依赖的课修了,像不像 java 中的 maven 依赖,一个jar包依赖另外一个jar包,想要在A jar包里用B jar包的东西,是不是得先把B jar包引入进来,才能用,同理,想修B课程,需要把A课程修了。如果出现循环依赖,则直接返回false,代表实现不了这种机制。

本题将采用图的拓扑序实现,至于什么是图?什么是有向图?什么是无相图?什么是图的拓扑序?可参考之前写的文章。

图介绍及图的遍历

图的拓扑序

2、实现

// 一个node,就是一个课程
// name是课程的编号
// in是课程的入度
// 图的拓扑结构
public static class Node {
    public int name;
    public int in;
    public ArrayList<Node> nexts;

    public Node(int n) {
        name = n;
        in = 0;
        nexts = new ArrayList<>();
    }
}

public static boolean canFinish(int numCourses, int[][] prerequisites) {
    if (prerequisites == null || prerequisites.length == 0) {
        return true;
    }
    // key:课程的编号,value:课程Node
    HashMap<Integer, Node> nodes = new HashMap<>(); // 存放课程的依赖关系
    for (int[] arr : prerequisites) { // 构建图的拓扑结构
        int to = arr[0];
        int from = arr[1];
        if (!nodes.containsKey(to)) {
            nodes.put(to, new Node(to));
        }
        if (!nodes.containsKey(from)) {
            nodes.put(from, new Node(from));
        }
        Node t = nodes.get(to);
        Node f = nodes.get(from);
        f.nexts.add(t);
        t.in++;
    }
    int needPrerequisiteNums = nodes.size();
    Queue<Node> zeroInQueue = new LinkedList<>();
    for (Node node : nodes.values()) {
        if (node.in == 0) { // 依次入度为0的课进队列
            zeroInQueue.add(node); 
        }
    }
    int count = 0;
    while (!zeroInQueue.isEmpty()) { // 依次入度为0的课出队列
        Node cur = zeroInQueue.poll();
        count++;
        for (Node next : cur.nexts) {
            if (--next.in == 0) {
                zeroInQueue.add(next);
            }
        }
    }
    // 只要不相等,则说明存在循环依赖的课
    return count == needPrerequisiteNums;
}

二、课程表问题 II

现在你总共有 numCourses 门课需要选,记为 0 到 numCourses - 1。给你一个数组 prerequisites ,其中 prerequisites[i] = [ai, bi] ,表示在选修课程 ai 前 必须 先选修 bi 。

  • 例如,想要学习课程 0 ,你需要先完成课程 1 ,我们用一个匹配来表示:[0,1] 。

返回你为了学完所有课程所安排的学习顺序。可能会有多个正确的顺序,你只要返回 任意一种 就可以了。如果不可能完成所有课程,返回 一个空数组 。

示例 1

输入:numCourses = 2, prerequisites = [[1,0]]
输出:[0,1]
解释:总共有 2 门课程。要学习课程 1,你需要先完成课程 0。因此,正确的课程顺序为 [0,1] 。

示例 2

输入:numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]
输出:[0,2,1,3]
解释:总共有 4 门课程。要学习课程 3,你应该先完成课程 1 和课程 2。并且课程 1 和课程 2 都应该排在课程 0 之后。
因此,一个正确的课程顺序是 [0,1,2,3] 。另一个正确的排序是 [0,2,1,3] 。

示例 3

输入:numCourses = 1, prerequisites = []
输出:[0]

leetcode

1、分析

换汤不换药,本质还是图的拓扑序,只不过把图的拓扑序收集起来返回即可,图的拓扑序不唯一

图的拓扑序实现:利用图的结构很好实现,入度为0的进入队列,入度为0代表没有边指向它,这是最核心的思路。

图的拓扑序,不止一种拓扑序,返回图的拓扑序。

2、实现

public static class Node {
    public int name;
    public int in;
    public ArrayList<Node> nexts;

    public Node(int n) {
        name = n;
        in = 0;
        nexts = new ArrayList<>();
    }
}

public int[] findOrder(int numCourses, int[][] prerequisites) {
    int[] ans = new int[numCourses];
    for (int i = 0; i < numCourses; i++) {
        ans[i] = i;
    }
    if (prerequisites == null || prerequisites.length == 0) {
        return ans;
    }
    HashMap<Integer, Node> nodes = new HashMap<>();
    for (int[] arr : prerequisites) {
        int to = arr[0];
        int from = arr[1];
        if (!nodes.containsKey(to)) {
            nodes.put(to, new Node(to));
        }
        if (!nodes.containsKey(from)) {
            nodes.put(from, new Node(from));
        }
        Node t = nodes.get(to);
        Node f = nodes.get(from);
        f.nexts.add(t);
        t.in++;
    }
    int index = 0;
    Queue<Node> zeroInQueue = new LinkedList<>();
    for (int i = 0; i < numCourses; i++) {
        if (!nodes.containsKey(i)) {
            ans[index++] = i;
        } else {
            if (nodes.get(i).in == 0) {
                zeroInQueue.add(nodes.get(i));
            }
        }
    }
    int needPrerequisiteNums = nodes.size();
    int count = 0;
    while (!zeroInQueue.isEmpty()) {
        Node cur = zeroInQueue.poll();
        ans[index++] = cur.name;
        count++;
        for (Node next : cur.nexts) {
            if (--next.in == 0) {
                zeroInQueue.add(next);
            }
        }
    }
    return count == needPrerequisiteNums ? ans : new int[0];
}

三、课程表问题 III

这里有 n 门不同的在线课程,按从 1 到 n 编号。给你一个数组 courses ,其中 courses[i] = [durationi, lastDayi] 表示第 i 门课将会 持续 上 durationi 天课,并且必须在不晚于 lastDayi 的时候完成。

你的学期从第 1 天开始。且不能同时修读两门及两门以上的课程。

返回你最多可以修读的课程数目。

示例 1:

输入:courses = [[100, 200], [200, 1300], [1000, 1250], [2000, 3200]]
输出:3
解释:
这里一共有 4 门课程,但是你最多可以修 3 门:
首先,修第 1 门课,耗费 100 天,在第 100 天完成,在第 101 天开始下门课。
第二,修第 3 门课,耗费 1000 天,在第 1100 天完成,在第 1101 天开始下门课程。
第三,修第 2 门课,耗时 200 天,在第 1300 天完成。
第 4 门课现在不能修,因为将会在第 3300 天完成它,这已经超出了关闭日期。

示例 2:

输入: courses = [[1,2]]
输出: 1

示例 3:

输入: courses = [[3,2],[4,3]]
输出: 0

leetcode

1、分析

题目要求只能一门一门的修课,不能同时修两门以上的课。

根据课程的截止时长从小到大排序,再准备一个大根堆(课程时长从大到小排序)。

大根堆代表什么? 哪些课程考虑去修,当前课程修的时长没超过截止时长的话,直接进大根堆,否则就是不满足题意(课程修的时长大于课程的截止时长),比如要求3天内修完这门课,结果修了5天,显然不符合要求。

题目要求修的课越多越好,淘汰课时长的,收益都是一样的(都是能修一门课),那必然淘汰课程时长长的,才能修更多的课,也就是淘汰大根堆堆顶课程时长长的课,最终大根堆的大小就是最多能修多少门课。

贪心的体现:如果收益都一样,都能修一门课,那么自然把课程时长长的给淘汰掉,把课程时长短的留下,这是人类自然智慧的体现。

贪心的做法一般采用排序、堆结构实现。

本题采用的数据结构和算法:比较器(排序)+ 堆(大根堆)。

2、实现

public static int scheduleCourse(int[][] courses) {
    // courses[i]  = {花费,截止}
    Arrays.sort(courses, (a, b) -> a[1] - b[1]);
    // 花费时间的大根堆
    PriorityQueue<Integer> heap = new PriorityQueue<>((a, b) -> b - a);
    // 时间点
    int time = 0;
    for (int[] c : courses) {
        if (time + c[0] <= c[1]) { // 当前时间 + 花费 <= 截止时间的
            heap.add(c[0]);
            time += c[0];
        } else { // 当前时间 + 花费 > 截止时间的, 只有淘汰掉某课,当前的课才能进来!
            if (!heap.isEmpty() && heap.peek() > c[0]) {
                // time -= heap.poll();
                // heap.add(c[0]);
                // time += c[0];
                heap.add(c[0]);
                time += c[0] - heap.poll();
            }
        }
    }
    return heap.size();
}