Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 5a62076

Browse files
feat: add swift implementation to lcp problem: No.62 (#3972)
1 parent 957336b commit 5a62076

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

‎lcp/LCP 62. 交通枢纽/README.md‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff 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 -->
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
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+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /