Skip to content

Commit 34e0877

Browse files
authored
Improved task 207
1 parent f8f9ecc commit 34e0877

File tree

1 file changed

+6
-9
lines changed
  • src/main/kotlin/g0201_0300/s0207_course_schedule

1 file changed

+6
-9
lines changed

Diff for: src/main/kotlin/g0201_0300/s0207_course_schedule/Solution.kt

+6-9
Original file line numberDiff line numberDiff line change
@@ -2,29 +2,26 @@ package g0201_0300.s0207_course_schedule
22

33
// #Medium #Top_100_Liked_Questions #Top_Interview_Questions #Depth_First_Search
44
// #Breadth_First_Search #Graph #Topological_Sort #Big_O_Time_O(N)_Space_O(N)
5-
// #2022_09_09_Time_416_ms_(40.10%)_Space_48.5_MB_(75.40%)
5+
// #2023_12_31_Time_356_ms_(10.58%)_Space_38.1_MB_(97.12%)
66

77
class Solution {
88
fun canFinish(numCourses: Int, prerequisites: Array<IntArray>): Boolean {
9-
val adj: Array<ArrayList<Int>?> = arrayOfNulls<ArrayList<Int>>(numCourses)
10-
for (i in 0 until numCourses) {
11-
adj[i] = ArrayList()
12-
}
9+
val adj: Array<ArrayList<Int>> = Array(numCourses) { ArrayList() }
1310
for (pre in prerequisites) {
14-
adj[pre[1]]?.add(pre[0])
11+
adj[pre[1]].add(pre[0])
1512
}
1613
val colors = IntArray(numCourses)
1714
for (i in 0 until numCourses) {
18-
if (colors[i] == WHITE && !adj[i]?.isEmpty()!! && hasCycle(adj, i, colors)) {
15+
if (colors[i] == WHITE && adj[i].isNotEmpty() && hasCycle(adj, i, colors)) {
1916
return false
2017
}
2118
}
2219
return true
2320
}
2421

25-
private fun hasCycle(adj: Array<ArrayList<Int>?>, node: Int, colors: IntArray): Boolean {
22+
private fun hasCycle(adj: Array<ArrayList<Int>>, node: Int, colors: IntArray): Boolean {
2623
colors[node] = GRAY
27-
for (nei in adj[node]!!) {
24+
for (nei in adj[node]) {
2825
if (colors[nei] == GRAY) {
2926
return true
3027
}

0 commit comments

Comments
 (0)