File tree 2 files changed +47
-0
lines changed
lcof2/剑指 Offer II 074. 合并区间
2 files changed +47
-0
lines changed Original file line number Diff line number Diff line change @@ -188,6 +188,32 @@ public class Solution {
188
188
}
189
189
```
190
190
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
+
191
217
<!-- tabs: end -->
192
218
193
219
<!-- solution: end -->
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments