Problem: 207. 课程表
文章目录
- 思路
- 复杂度
- Code
思路
👨🏫 三叶题解
复杂度
时间复杂度: O ( n + m ) O(n+m) O(n+m)
空间复杂度: O ( n + m ) O(n+m) O(n+m)
Code
class Solution{int N = 100010, M = 5010, idx;int[] in = new int[N];// in[i] 表示节点 i 的入度int[] h = new int[N];int[] e = new int[N];int[] ne = new int[N];// 添加一条边 a --> bvoid add(int a, int b){e[idx] = b;ne[idx] = h[a];h[a] = idx++;in[b]++;}public boolean canFinish(int n, int[][] g){Arrays.fill(h, -1);//初始化头结点for (int[] a : g)add(a[1], a[0]);int ans = 0;Queue<Integer> q = new LinkedList<>();for (int i = 0; i < n; i++)if (in[i] == 0)q.add(i);while (!q.isEmpty()){int x = q.poll();ans++;for (int i = h[x]; i != -1; i = ne[i]){int j = e[i];in[j]--;if (in[j] == 0)q.add(j);}}return ans == n;}
}