LC.P630[课程表III]

方法一:贪心+优先队列

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public int scheduleCourse(int[][] courses) {
Arrays.sort(courses, (a, b) -> a[1] - b[1]);
PriorityQueue<Integer> q = new PriorityQueue<>((a, b) -> b - a);
int sum = 0;
for (int[] course : courses) {
int duration = course[0], lastDay = course[1];
sum += duration;
q.offer(duration);
if (sum > lastDay) sum -= q.poll();
}
return q.size();
}
}
  • 时间复杂度:$O(nlogn)$
  • 空间复杂度:$O(n)$