Join GitHub today
GitHub is home to over 50 million developers working together to host and review code, manage projects, and build software together.
Sign up[LeetCode] 630. Course Schedule III #630
Open
Comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There are
n
different online courses numbered from1
ton
. Each course has some duration(course length)t
and closed ondth
day. A course should be taken continuously fort
days and must be finished before or on thedth
day. You will start at the1st
day.Given
n
online courses represented by pairs(t,d)
, your task is to find the maximal number of courses that can be taken.Example:
Note:
这道题给了我们许多课程,每个课程有两个参数,第一个是课程的持续时间,第二个是课程的最晚结束日期,让我们求最多能上多少门课。博主尝试了递归的暴力破解,TLE了。这道题给的提示是用贪婪算法,那么我们首先给课程排个序,按照结束时间的顺序来排序,我们维护一个当前的时间,初始化为0,再建立一个优先数组,然后我们遍历每个课程,对于每一个遍历到的课程,当前时间加上该课程的持续时间,然后将该持续时间放入优先数组中,然后我们判断如果当前时间大于课程的结束时间,说明这门课程无法被完成,我们并不是直接减去当前课程的持续时间,而是取出优先数组的顶元素,即用时最长的一门课,这也make sense,因为我们的目标是尽可能的多上课,既然非要去掉一门课,那肯定是去掉耗时最长的课,这样省下来的时间说不定能多上几门课呢,最后返回优先队列中元素的个数就是能完成的课程总数啦,参见代码如下:
类似题目:
Course Schedule II
Course Schedule
参考资料:
https://discuss.leetcode.com/topic/93790/short-java-code-using-priorityqueue
https://discuss.leetcode.com/topic/93712/python-straightforward-with-explanation
https://discuss.leetcode.com/topic/93884/c-short-elegant-o-nlogn-time-o-k-space-solution/2
LeetCode All in One 题目讲解汇总(持续更新中...)