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 c310525

Browse files
feat: add swift implementation to lcof2 problem: No.118 (doocs#3696)
1 parent 17af691 commit c310525

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

‎lcof2/剑指 Offer II 118. 多余的边/README.md‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,36 @@ func findRedundantConnection(edges [][]int) []int {
164164
}
165165
```
166166

167+
#### Swift
168+
169+
```swift
170+
class Solution {
171+
private var parent: [Int] = []
172+
173+
func findRedundantConnection(_ edges: [[Int]]) -> [Int] {
174+
parent = Array(0..<1010)
175+
176+
for edge in edges {
177+
let a = edge[0]
178+
let b = edge[1]
179+
180+
if find(a) == find(b) {
181+
return edge
182+
}
183+
parent[find(a)] = find(b)
184+
}
185+
return []
186+
}
187+
188+
private func find(_ x: Int) -> Int {
189+
if parent[x] != x {
190+
parent[x] = find(parent[x])
191+
}
192+
return parent[x]
193+
}
194+
}
195+
```
196+
167197
<!-- tabs:end -->
168198

169199
<!-- solution:end -->
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class Solution {
2+
private var parent: [Int] = []
3+
4+
func findRedundantConnection(_ edges: [[Int]]) -> [Int] {
5+
parent = Array(0..<1010)
6+
7+
for edge in edges {
8+
let a = edge[0]
9+
let b = edge[1]
10+
11+
if find(a) == find(b) {
12+
return edge
13+
}
14+
parent[find(a)] = find(b)
15+
}
16+
return []
17+
}
18+
19+
private func find(_ x: Int) -> Int {
20+
if parent[x] != x {
21+
parent[x] = find(parent[x])
22+
}
23+
return parent[x]
24+
}
25+
}

0 commit comments

Comments
(0)

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