-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0057.Insert Interval.swift
43 lines (34 loc) · 1.15 KB
/
0057.Insert Interval.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class Solution {
func insert(_ intervals: [[Int]], _ newInterval: [Int]) -> [[Int]] {
var intervals = intervals
if let idx = intervals.firstIndex { $0[0] > newInterval[0] } {
intervals.insert(newInterval, at: idx)
} else {
intervals.append(newInterval)
}
return merge(intervals)
}
private func merge(_ intervals: [[Int]]) -> [[Int]] {
var result = [[Int]]()
var current = intervals[0]
var idx = 1
while idx < intervals.count {
let next = intervals[idx]
if current[0] == next[0] {
current = [current[0], max(current[1], next[1])]
} else {
if current[1] < next[0] {
result.append(current)
current = intervals[idx]
} else {
current = [current[0], max(current[1], next[1])]
}
}
idx += 1
}
if result.last != current {
result.append(current)
}
return result
}
}