diff --git "a/lcp/LCP 62. \344\272\244\351\200\232\346\236\242\347\272\275/README.md" "b/lcp/LCP 62. \344\272\244\351\200\232\346\236\242\347\272\275/README.md" index 348f106b5e995..690d01b9e1c20 100644 --- "a/lcp/LCP 62. \344\272\244\351\200\232\346\236\242\347\272\275/README.md" +++ "b/lcp/LCP 62. \344\272\244\351\200\232\346\236\242\347\272\275/README.md" @@ -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 --> diff --git "a/lcp/LCP 62. \344\272\244\351\200\232\346\236\242\347\272\275/Solution.swift" "b/lcp/LCP 62. \344\272\244\351\200\232\346\236\242\347\272\275/Solution.swift" new file mode 100644 index 0000000000000..dca4332f4a733 --- /dev/null +++ "b/lcp/LCP 62. \344\272\244\351\200\232\346\236\242\347\272\275/Solution.swift" @@ -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 + } +} \ No newline at end of file