-
Notifications
You must be signed in to change notification settings - Fork 20
/
MergeIntervals.swift
52 lines (39 loc) · 1.32 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
46
47
48
49
50
51
52
//
// MergeIntervals.swift
// LeetCode
//
// Created by 黎赵太郎 on 07/01/2018.
// Copyright © 2018 lizhaotailang. All rights reserved.
//
import Foundation
class MergeIntervals {
func merge(_ intervals: [Interval]) -> [Interval] {
if intervals.isEmpty || intervals.count == 1 {
return intervals
}
var results = Array<Interval>.init()
var newIntervals = intervals.sorted{ $0.start < $1.start}
results.append(newIntervals[0])
var i = 1
while i < newIntervals.count {
if results[results.count - 1].end >= newIntervals[i].start {
results[results.count - 1].end = max(results[results.count - 1].end, newIntervals[i].end)
} else {
results.append(newIntervals[i])
}
i += 1
}
return results
}
public class Interval: Equatable {
public var start: Int
public var end: Int
public init(_ start: Int, _ end: Int) {
self.start = start
self.end = end
}
public static func ==(lhs: MergeIntervals.Interval, rhs: MergeIntervals.Interval) -> Bool {
return lhs.start == rhs.start && lhs.end == rhs.end
}
}
}