Skip to content

Commit 3913dfb

Browse files
authored
feat: add swift implementation to lcof2 problem: No.074 (#3307)
1 parent a245b03 commit 3913dfb

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

lcof2/剑指 Offer II 074. 合并区间/README.md

+26
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,32 @@ public class Solution {
188188
}
189189
```
190190

191+
#### Swift
192+
193+
```swift
194+
class Solution {
195+
func merge(_ intervals: [[Int]]) -> [[Int]] {
196+
guard !intervals.isEmpty else { return [] }
197+
198+
let intervals = intervals.sorted { $0[0] < $1[0] }
199+
var result: [[Int]] = []
200+
201+
var currentInterval = intervals[0]
202+
for interval in intervals.dropFirst() {
203+
if currentInterval[1] < interval[0] {
204+
result.append(currentInterval)
205+
currentInterval = interval
206+
} else {
207+
currentInterval[1] = max(currentInterval[1], interval[1])
208+
}
209+
}
210+
result.append(currentInterval)
211+
212+
return result
213+
}
214+
}
215+
```
216+
191217
<!-- tabs:end -->
192218

193219
<!-- solution:end -->
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
class Solution {
2+
func merge(_ intervals: [[Int]]) -> [[Int]] {
3+
guard !intervals.isEmpty else { return [] }
4+
5+
let intervals = intervals.sorted { $0[0] < $1[0] }
6+
var result: [[Int]] = []
7+
8+
var currentInterval = intervals[0]
9+
for interval in intervals.dropFirst() {
10+
if currentInterval[1] < interval[0] {
11+
result.append(currentInterval)
12+
currentInterval = interval
13+
} else {
14+
currentInterval[1] = max(currentInterval[1], interval[1])
15+
}
16+
}
17+
result.append(currentInterval)
18+
19+
return result
20+
}
21+
}

0 commit comments

Comments
 (0)