1、题目
这里有 n 门不同的在线课程,他们按从 1 到 n 编号。每一门课程有一定的持续上课时间(课程时间)t 以及关闭时间第 d 天。一门课要持续学习 t 天直到第 d 天时要完成,你将会从第 1 天开始。
给出 n 个在线课程用 (t, d) 对表示。你的任务是找出最多可以修几门课。
示例:
输入: [[100, 200], [200, 1300], [1000, 1250], [2000, 3200]]
输出: 3
解释:
这里一共有 4 门课程, 但是你最多可以修 3 门:
首先, 修第一门课时, 它要耗费 100 天,你会在第 100 天完成, 在第 101 天准备下门课。
第二, 修第三门课时, 它会耗费 1000 天,所以你将在第 1100 天的时候完成它, 以及在第 1101 天开始准备下门课程。
第三, 修第二门课时, 它会耗时 200 天,所以你将会在第 1300 天时完成它。
第四门课现在不能修,因为你将会在第 3300 天完成它,这已经超出了关闭日期。
提示:
整数 1 <= d, t, n <= 10,000 。
你不能同时修两门课程。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/course-schedule-iii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2、思路
通过观察可知:需要一直累加所需学习时间之和,与每一个新的deadline比较,一旦发现大于deadline,那么我们就删除我们已经遍历过这几个中花费时间最久的。(很可惜,初学java的我想方设法把冒泡排序改成了快速排序,却不知道java有已经写好的函数。很遗憾,最后一直都是“时间超过限制。”)
3、我的错误代码(纪念)
//自己生产的冒泡排序
// int[] temp = new int[1];
// for(int i = 0; i < courses.length - 1; i++)
// {
// for(int j = courses.length - 1; j >= i + 1; j--)
// {
// if(courses[j][1]<courses[j-1][1])
// {
// temp = courses[j];
// courses[j] = courses[j-1];
// courses[j-1] = temp;
// }
// }
// }
class Solution {
public static void quicksort(int left, int right, int[][]courses) {
int i, j;
int[] temp;
int t[];
if(left > right)
return;
temp = courses[left]; //temp中存的就是基准数
i = left;
j = right;
while(i != j) { //顺序很重要,要先从右边开始找
while(courses[j][1] >= temp[1] && i < j)
j--;
while(courses[i][1] <= temp[1] && i < j)//再找右边的
i++;
if(i < j)//交换两个数在数组中的位置
{
t = courses[i];
courses[i] = courses[j];
courses[j] = t;
}
}
//最终将基准数归位
courses[left] = courses[i];
courses[i] = temp;
quicksort(left, i-1,courses);//继续处理左边的,这里是一个递归的过程
quicksort(i+1, right,courses);//继续处理右边的 ,这里是一个递归的过程
}
public static int scheduleCourse(int[][] courses) {
quicksort(0,courses.length-1,courses);
int sum_cost = 0;
int cut = 0;
int length = courses.length;
for(int i = 0; i < length; i++)
{
int max = 0;
cut++;
sum_cost += courses[i][0];
if(sum_cost <= courses[i][1])
{
continue;
}
else
{
int flag = 0;
int j = i;
for(int k = 0; k <= j; k++)
{
if(courses[k][0] >= max)
{
flag = k;
max = courses[k][0];
}
}
sum_cost -= courses[flag][0];
cut--;
int t;
for(t = flag; t < courses.length - 1; t++)
{
courses[t] = courses[t+1];
}
courses[t] = new int[]{0,0};
i--;
length--;
}
}
System.out.println(cut);
return cut;
}
}