forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MergeIntervals.swift
45 lines (39 loc) · 1.14 KB
/
MergeIntervals.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
44
45
/**
* Question Link: https://leetcode.com/problems/merge-intervals/
* Primary idea: Sort the original intervals and then append them one by one
* Time Complexity: O(nlogn), Space Complexity: O(n)
*
* Definition for an interval.
* public class Interval {
* public var start: Int
* public var end: Int
* public init(_ start: Int, _ end: Int) {
* self.start = start
* self.end = end
* }
* }
*/
class MergeIntervals {
func merge(intervals: [Interval]) -> [Interval] {
guard intervals.count > 0 else {
return intervals
}
var intervals = intervals.sort() {
if $0.start != $1.start {
return $0.start < $1.start
} else {
return $0.end < $1.end
}
}
var res = [intervals.first!]
for i in 1..<intervals.count {
let (last, current) = (res.last!, intervals[i])
if current.start > last.end {
res.append(current)
} else {
last.end = max(last.end, current.end)
}
}
return res
}
}