Skip to content

Commit 11f6cc6

Browse files
committed
solve problem
1 parent d9ed306 commit 11f6cc6

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

merge-intervals/delight010.swift

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
class Solution {
2+
// Time O(n log n)
3+
// Space O(n)
4+
func merge(_ intervals: [[Int]]) -> [[Int]] {
5+
if intervals.count <= 1 {
6+
return intervals
7+
}
8+
9+
let intervals = intervals.sorted { $0[0] <= $1[0] }
10+
var answer: [[Int]] = []
11+
var currentInterval: [Int] = []
12+
13+
for i in 0..<intervals.count {
14+
if currentInterval.isEmpty {
15+
currentInterval = intervals[i]
16+
}
17+
18+
if intervals[i][0] >= currentInterval[0] && intervals[i][0] <= currentInterval[1] {
19+
currentInterval = [currentInterval[0], max(currentInterval[1], intervals[i][1])]
20+
} else {
21+
answer.append(currentInterval)
22+
currentInterval = intervals[i]
23+
}
24+
}
25+
26+
answer.append(currentInterval)
27+
28+
return answer
29+
}
30+
}
31+

0 commit comments

Comments
 (0)