题目:
自己的理解: 我们可以从最后的结果来思考,如果我们已知最后的结果,那么我们可以推断最后结果的形式,以此来确定应该以什么方式排课。从推测结果可知,dth越小,数组越是排在前列,因为要求要有最多的课,如果dth小的排在后边,会浪费时间。所以可以对dth从小到大排列,然后从中依次挑选,然后检查是否可以排课,如果可以排课,那么当前数组中最大的dth一定大于等于所用时间,否则,则把已排课中占用时间最大的课,排除。然后再进行下一次挑选。这样到最后,得到的课数量便是能排课的最大数量。
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.
大概为,根据所给数组,求最大的排课数量是多少;
大神的算法:
public int scheduleCourse(int[][] courses) {
Arrays.sort(courses,(a,b)->a[1]-b[1]); //Sort the courses by their deadlines (Greedy! We have to deal with courses with early deadlines first)
PriorityQueue<Integer> pq=new PriorityQueue<>((a,b)->b-a);
int time=0;
for (int[] c:courses)
{
time+=c[0]; // add current course to a priority queue
pq.add(c[0]);
if (time>c[1]) time-=pq.poll(); //If time exceeds, drop the previous course which costs the most time. (That must be the best choice!)
}
return pq.size();
}
自己的理解: 我们可以从最后的结果来思考,如果我们已知最后的结果,那么我们可以推断最后结果的形式,以此来确定应该以什么方式排课。从推测结果可知,dth越小,数组越是排在前列,因为要求要有最多的课,如果dth小的排在后边,会浪费时间。所以可以对dth从小到大排列,然后从中依次挑选,然后检查是否可以排课,如果可以排课,那么当前数组中最大的dth一定大于等于所用时间,否则,则把已排课中占用时间最大的课,排除。然后再进行下一次挑选。这样到最后,得到的课数量便是能排课的最大数量。