Skip to content

Commit 5c5b5bf

Browse files
committed
课程表 II
1 parent e3abacc commit 5c5b5bf

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,7 @@
9696
| 206 | 链表 | [反转链表](src/main/java/algorithm/leetcode/Solution206.java) | 简单 |
9797
| 207 | 深度优先搜索、广度优先搜索、图、拓扑排序 | [课程表](src/main/java/algorithm/leetcode/Solution207.java) | 中等 |
9898
| 209 | 数组、双指针、二分查找 | [长度最小的子数组](src/main/java/algorithm/leetcode/Solution209.java) | 中等 |
99+
| 210 | 深度优先搜索、广度优先搜索、图、拓扑排序 | [课程表 II](src/main/java/algorithm/leetcode/Solution210.java) | 中等 |
99100
| 211 | 设计、字典数、回溯算法 | [添加与搜索单词 - 数据结构设计](src/main/java/algorithm/leetcode/Solution211.java) | 中等 |
100101
| 212 | 字典数、回溯算法 | [单词搜索 II](src/main/java/algorithm/leetcode/Solution212.java) | 困难 |
101102
| 213 | 动态规划 | [打家劫舍 II](src/main/java/algorithm/leetcode/Solution213.java) | 中等 |
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package algorithm.leetcode;
2+
3+
import java.util.LinkedList;
4+
import java.util.Queue;
5+
6+
/**
7+
* @author: mayuan
8+
* @desc: 课程表 II
9+
* @date: 2019/03/13
10+
*/
11+
public class Solution210 {
12+
public int[] findOrder(int numCourses, int[][] prerequisites) {
13+
if (numCourses == 0) {
14+
return null;
15+
}
16+
// Convert graph presentation from edges to indegree of adjacent list.
17+
int[] indegree = new int[numCourses];
18+
int[] order = new int[numCourses];
19+
int index = 0;
20+
// Indegree - how many prerequisites are needed.
21+
for (int i = 0; i < prerequisites.length; i++) {
22+
indegree[prerequisites[i][0]]++;
23+
}
24+
25+
Queue<Integer> queue = new LinkedList<Integer>();
26+
for (int i = 0; i < numCourses; i++) {
27+
if (indegree[i] == 0) {
28+
// Add the course to the order because it has no prerequisites.
29+
order[index++] = i;
30+
queue.offer(i);
31+
}
32+
}
33+
// How many courses don't need prerequisites.
34+
while (!queue.isEmpty()) {
35+
// Already finished this prerequisite course.
36+
int prerequisite = queue.poll();
37+
for (int i = 0; i < prerequisites.length; i++) {
38+
if (prerequisites[i][1] == prerequisite) {
39+
indegree[prerequisites[i][0]]--;
40+
if (indegree[prerequisites[i][0]] == 0) {
41+
// If indegree is zero, then add the course to the order.
42+
order[index++] = prerequisites[i][0];
43+
queue.offer(prerequisites[i][0]);
44+
}
45+
}
46+
}
47+
}
48+
49+
return (index == numCourses) ? order : new int[0];
50+
}
51+
}

0 commit comments

Comments
 (0)