题目描述:
There are n different online courses numbered from 1 to n. Each course has some duration(course length) t and closed on dth day. A course should be taken continuously for t days and must be finished before or on the dth day. You will start at the 1st day.
Given n online courses represented by pairs (t,d), your task is to find the maximal number of courses that can be taken.
示例:
Input: [[100, 200], [200, 1300], [1000, 1250], [2000, 3200]]
Output: 3
解题思路:
- 将课程按due time排序,due time排序在前的表示优先级较高,需要先完成;
- 遍历排序后的课程,若某个课程可在due time前结束,则将该课程的耗费时间加入调度list中,并更新已花费的时间consumingTIme的值;
- 若某个课程不可在due time前结束,则首先判断该课程耗费时间是否比list中最长的耗费时间还要长,若是,则不添加该课程;若不是,则删除list中最长的耗费时间并将该时间加入list中。
原理:
- 按due time排序可保证所有课程较好的时间顺序加入list; 若出现某个课程A的due time较小,但consuming time较长的课程,该课程会慢慢被后续consuming time较短的课程B替换掉;
- 且因为B的due time(d1)都比A的due time (d2)大,B的consuming time(c1)都比A的consuming time(c2)小;
- 且A在list中,所以当前时间+c2 < d2,那么当前时间+c1< d1肯定成立。所以B肯定可以替换A,且可以使得当前时间变小。所以这是一个最优策略。
源代码
class Solution(object):
def scheduleCourse(self, courses):
#用于查找list中的元素//二分查找
def findElement(l, s, e, x):
if s > e:
return s
mid = int((s + e) / 2)
if l[mid] < x:
if mid == len(l) - 1:
return mid + 1
if l[mid + 1] >= x:
return mid + 1
return findElement(l, mid + 1, e, x)
if l[mid] > x:
if mid == 0:
return 0
if l[mid - 1] <= x:
return mid
return findElement(l, s, mid - 1, x)
return mid
if courses == []:
return 0
#按照结束时间排序
courses.sort(key = lambda x : x[1])
res = [courses[0][0]]
#已花去的时间
consumingTimes = res[0]
for i in courses[1:]:
#若课程可在due time前完成,则直接加入list
if consumingTimes + i[0] <= i[1]:
pos = findElement(res, 0, len(res) - 1, i[0])
if pos == len(res):
res.append(i[0])
else:
res.insert(pos, i[0])
consumingTimes += i[0]
#否则若该课程耗费时间较少,则替换list中耗费时间最长的课程
else:
if i[0] < res[-1]:
consumingTimes += i[0] - res[-1]
del res[-1]
pos = findElement(res, 0, len(res) - 1, i[0])
if pos == len(res):
res.append(i[0])
else:
res.insert(pos, i[0])
return len(res)