Skip to content
This repository was archived by the owner on Apr 27, 2025. It is now read-only.

Commit 4c19145

Browse files
committed
56. Merge Intervals
1 parent df09c78 commit 4c19145

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

56. Merge Intervals.md

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
# 56. Merge Intervals
2+
3+
### 2017-03-28
4+
5+
Given a collection of intervals, merge all overlapping intervals.
6+
7+
For example,
8+
Given `[1,3],[2,6],[8,10],[15,18]`,
9+
return `[1,6],[8,10],[15,18]`.
10+
11+
12+
13+
# Solution
14+
15+
```swift
16+
/**
17+
* Definition for an interval.
18+
* public class Interval {
19+
* public var start: Int
20+
* public var end: Int
21+
* public init(_ start: Int, _ end: Int) {
22+
* self.start = start
23+
* self.end = end
24+
* }
25+
* }
26+
*/
27+
class Solution {
28+
func merge(_ intervals: [Interval]) -> [Interval] {
29+
guard intervals.count > 0 else { return [] }
30+
var temp = intervals.sorted { $0.0.start < $0.1.start}
31+
var res = [Interval]()
32+
var start = temp[0].start
33+
var end = temp[0].end
34+
for iv in temp {
35+
if iv.start <= end {
36+
end = max(iv.end, end)
37+
} else {
38+
res.append(Interval(start, end))
39+
start = iv.start
40+
end = iv.end
41+
}
42+
}
43+
res.append(Interval(start, end))
44+
return res
45+
46+
}
47+
}
48+
```
49+

0 commit comments

Comments
 (0)