Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add swift implementation to lcp problem: No.62 #3972

Merged
merged 1 commit into from
Jan 21, 2025
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