File tree Expand file tree Collapse file tree 2 files changed +65
-0
lines changed Expand file tree Collapse file tree 2 files changed +65
-0
lines changed Original file line number Diff line number Diff line change @@ -205,6 +205,41 @@ function transportationHub(path: number[][]): number {
205205}
206206```
207207
208+ #### Swift
209+
210+ ``` swift
211+ class Solution {
212+ func transportationHub (_ path : [[Int ]]) -> Int {
213+ var inDegree = [Int : Int ]()
214+ var outDegree = [Int : Int ]()
215+ var nodeSet = Set < Int > ()
216+ var visitedEdges = Set < String > ()
217+
218+ for p in path {
219+ let a = p[0 ]
220+ let b = p[1 ]
221+ let edgeKey = " \( a ) -\( b ) "
222+
223+ if ! visitedEdges.contains (edgeKey) {
224+ visitedEdges.insert (edgeKey)
225+ nodeSet.insert (a)
226+ nodeSet.insert (b)
227+ inDegree[b, default : 0 ] += 1
228+ outDegree[a, default : 0 ] += 1
229+ }
230+ }
231+
232+ for node in nodeSet {
233+ if inDegree[node, default : 0 ] == nodeSet.count - 1 && outDegree[node, default : 0 ] == 0 {
234+ return node
235+ }
236+ }
237+
238+ return -1
239+ }
240+ }
241+ ```
242+
208243<!-- tabs: end -->
209244
210245<!-- solution: end -->
Original file line number Diff line number Diff line change 1+ class Solution {
2+ func transportationHub( _ path: [ [ Int ] ] ) -> Int {
3+ var inDegree = [ Int: Int] ( )
4+ var outDegree = [ Int: Int] ( )
5+ var nodeSet = Set < Int > ( )
6+ var visitedEdges = Set < String > ( )
7+
8+ for p in path {
9+ let a = p [ 0 ]
10+ let b = p [ 1 ]
11+ let edgeKey = " \( a) - \( b) "
12+
13+ if !visitedEdges. contains ( edgeKey) {
14+ visitedEdges. insert ( edgeKey)
15+ nodeSet. insert ( a)
16+ nodeSet. insert ( b)
17+ inDegree [ b, default: 0 ] += 1
18+ outDegree [ a, default: 0 ] += 1
19+ }
20+ }
21+
22+ for node in nodeSet {
23+ if inDegree [ node, default: 0 ] == nodeSet. count - 1 && outDegree [ node, default: 0 ] == 0 {
24+ return node
25+ }
26+ }
27+
28+ return - 1
29+ }
30+ }
You can’t perform that action at this time.
0 commit comments