-
Notifications
You must be signed in to change notification settings - Fork 169
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
76 additions
and
0 deletions.
There are no files selected for viewing
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
public class Solution { | ||
|
||
static class Vertex { | ||
|
||
int id; | ||
|
||
Vertex(int id){ | ||
this.id = id; | ||
} | ||
|
||
Set<Integer> in = new HashSet<>(); | ||
Set<Integer> out = new HashSet<>(); | ||
|
||
boolean isSink(){ | ||
return out.isEmpty(); | ||
} | ||
} | ||
|
||
Vertex safe(Vertex[] G, int id){ | ||
if(G[id] == null){ | ||
G[id] = new Vertex(id); | ||
} | ||
|
||
return G[id]; | ||
} | ||
|
||
public int[] findOrder(int numCourses, int[][] prerequisites) { | ||
Vertex[] G = new Vertex[numCourses]; | ||
|
||
for(int[] p : prerequisites){ | ||
safe(G, p[0]).out.add(p[1]); | ||
safe(G, p[1]).in.add(p[0]); | ||
} | ||
|
||
Set<Vertex> S = Arrays.stream(G) | ||
.filter(v -> v != null) | ||
.collect(Collectors.toSet()); | ||
|
||
|
||
LinkedHashSet<Integer> order = new LinkedHashSet<>(numCourses); | ||
|
||
loop: | ||
while(!S.isEmpty()){ | ||
|
||
for(Vertex v : S){ | ||
if(v.isSink()){ | ||
order.add(v.id); | ||
|
||
S.remove(v); | ||
|
||
for(int i : v.in){ | ||
G[i].out.remove(v.id); | ||
} | ||
|
||
continue loop; | ||
} | ||
} | ||
|
||
return new int[]{}; | ||
} | ||
|
||
// fill courses not in G | ||
order.addAll(IntStream.range(0, numCourses).boxed().collect(Collectors.toSet())); | ||
|
||
return order.stream() | ||
.mapToInt(i -> i) | ||
.toArray(); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
--- | ||
layout: solution | ||
title: Course Schedule II | ||
date: 2015-05-14 00:31:26+08:00 | ||
leetcode_id: 210 | ||
--- | ||
{% include_relative README.md %} |