forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MergeIntervals.swift
44 lines (39 loc) · 1.13 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
/**
* 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] {
var result = [Interval]()
let intervals = intervals.sorted {
if $0.start != $1.start {
return $0.start < $1.start
} else {
return $0.end < $1.end
}
}
for interval in intervals {
guard let last = result.last else {
result.append(interval)
continue
}
if last.end < interval.start {
result.append(interval)
} else {
last.end = max(last.end, interval.end)
}
}
return result
}
}