【力扣】课程表系列
Leetcode 0207 课程表
题目描述:Leetcode 0207 课程表
分析
-
本题的考点:拓扑排序。
-
关于拓扑排序可以参考:网址。
代码
- C++
class Solution {
public:
bool canFinish(int n, vector<vector<int>> &edges) {
vector<vector<int>> g(n);
vector<int> d(n); // 存储入度
for (auto &e : edges) {
int b = e[0], a = e[1];
g[a].push_back(b);
d[b]++;
}
queue<int> q;
for (int i = 0; i < n; i++)
if (d[i] == 0)
q.push(i);
int cnt = 0;
while (q.size()) {
auto a = q.front(); q.pop();
cnt++;
for (auto b : g[a])
if (--d[b] == 0)
q.push(b);
}
return cnt == n;
}
};
- Java
class Solution {
public boolean canFinish(int n, int[][] edges) {
List<List<Integer>> g = new ArrayList<>();
for (int i = 0; i < n; i++) g.add(new ArrayList<>());
int[] d = new int[n]; // 存储入度
for (int[] e : edges) {
int b = e[0], a = e[1];
g.get(a).add(b);
d[b]++;
}
Queue<Integer> q = new LinkedList<>();
for (int i = 0; i < n; i++)
if (d[i] == 0)
q.add(i);
int cnt = 0;
while (!q.isEmpty()) {
int a = q.remove();
cnt++;
for (int b : g.get(a))
if (--d[b] == 0)
q.add(b);
}
return cnt == n;
}
}
时空复杂度分析
-
时间复杂度: O ( n ) O(n) O(n),
n
为课程数量。 -
空间复杂度: O ( n ) O(n) O(n)。
Leetcode 0210 课程表 II
题目描述:Leetcode 0210 课程表 II
分析
-
本题的考点:拓扑排序。
-
关于拓扑排序可以参考:网址。
-
本题相对于Leetcode 0207 课程表,就是让求出拓扑排序的方案。队列中的元素出队顺序就是一种合法方案,记录下来即可
代码
- C++
class Solution {
public:
vector<int> findOrder(int n, vector<vector<int>> &edges) {
vector<vector<int>> g(n);
vector<int> d(n); // 入度
for (auto &e : edges) {
auto b = e[0], a = e[1];
g[a].push_back(b);
d[b]++;
}
queue<int> q;
for (int i = 0; i < n; i++)
if (d[i] == 0)
q.push(i);
vector<int> res;
while (q.size()) {
auto a = q.front();
q.pop();
res.push_back(a);
for (auto b : g[a])
if (--d[b] == 0)
q.push(b);
}
if (res.size() < n) res = {};
return res;
}
};
- Java
class Solution {
public int[] findOrder(int n, int[][] edges) {
List<List<Integer>> g = new ArrayList<>();
for (int i = 0; i < n; i++) g.add(new ArrayList<>());
int[] d = new int[n]; // 存储入度
for (int[] e : edges) {
int b = e[0], a = e[1];
g.get(a).add(b);
d[b]++;
}
Queue<Integer> q = new LinkedList<>();
for (int i = 0; i < n; i++)
if (d[i] == 0)
q.add(i);
int[] res = new int[n];
int cnt = 0;
while (!q.isEmpty()) {
int a = q.remove();
res[cnt++] = a;
for (int b : g.get(a))
if (--d[b] == 0)
q.add(b);
}
if (cnt < n) return new int[]{};
return res;
}
}
时空复杂度分析
-
时间复杂度: O ( n ) O(n) O(n),
n
为课程数量。 -
空间复杂度: O ( n ) O(n) O(n)。
Leetcode 0630 课程表 III
分析
-
本题的考点:贪心、堆。
-
按照截止时间从小到大排序,从前向后依次考察每门课程,如果能选则这门课程则选择,不能选的话则必须删除一门课程,删除包含当前课程的需要用时最长的课程即可。
-
能选则选:即如果加入这门课程后总用时没有超出当前截止日期。
代码
- C++
class Solution {
public:
int scheduleCourse(vector<vector<int>> &courses) {
sort(courses.begin(), courses.end(), [](vector<int> &a, vector<int> &b) {
return a[1] < b[1];
});
priority_queue<int> heap;
int tot = 0; // 选出的课程用时
for (auto &c : courses) {
tot += c[0];
heap.push(c[0]);
if (tot > c[1]) {
tot -= heap.top();
heap.pop();
}
}
return heap.size();
}
};
时空复杂度分析
-
时间复杂度: O ( n × l o g ( n ) ) O(n \times log(n)) O(n×log(n)),
n
为数组长度。 -
空间复杂度: O ( n ) O(n) O(n)。