Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions lcp/LCP 62. 交通枢纽/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,41 @@ function transportationHub(path: number[][]): number {
}
```

#### Swift

```swift
class Solution {
func transportationHub(_ path: [[Int]]) -> Int {
var inDegree = [Int: Int]()
var outDegree = [Int: Int]()
var nodeSet = Set<Int>()
var visitedEdges = Set<String>()

for p in path {
let a = p[0]
let b = p[1]
let edgeKey = "\(a)-\(b)"

if !visitedEdges.contains(edgeKey) {
visitedEdges.insert(edgeKey)
nodeSet.insert(a)
nodeSet.insert(b)
inDegree[b, default: 0] += 1
outDegree[a, default: 0] += 1
}
}

for node in nodeSet {
if inDegree[node, default: 0] == nodeSet.count - 1 && outDegree[node, default: 0] == 0 {
return node
}
}

return -1
}
}
```

<!-- tabs:end -->

<!-- solution:end -->
Expand Down
30 changes: 30 additions & 0 deletions lcp/LCP 62. 交通枢纽/Solution.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
class Solution {
func transportationHub(_ path: [[Int]]) -> Int {
var inDegree = [Int: Int]()
var outDegree = [Int: Int]()
var nodeSet = Set<Int>()
var visitedEdges = Set<String>()

for p in path {
let a = p[0]
let b = p[1]
let edgeKey = "\(a)-\(b)"

if !visitedEdges.contains(edgeKey) {
visitedEdges.insert(edgeKey)
nodeSet.insert(a)
nodeSet.insert(b)
inDegree[b, default: 0] += 1
outDegree[a, default: 0] += 1
}
}

for node in nodeSet {
if inDegree[node, default: 0] == nodeSet.count - 1 && outDegree[node, default: 0] == 0 {
return node
}
}

return -1
}
}
Loading