-
Notifications
You must be signed in to change notification settings - Fork 0
/
056.go
64 lines (54 loc) · 1.09 KB
/
056.go
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
53
54
55
56
57
58
59
60
61
62
63
64
package p056
import (
"sort"
)
/**
Given a collection of intervals, merge all overlapping intervals.
For example,
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].
*/
/**
* Definition for an interval.
* type Interval struct {
* Start int
* End int
* }
*/
type Interval struct {
Start int
End int
}
type Intervals []Interval
func (is Intervals) Len() int {
return len(is)
}
// Less reports whether the element with
// index i should sort before the element with index j.
func (is Intervals) Less(i, j int) bool {
return is[i].Start < is[j].Start
}
// Swap swaps the elements with indexes i and j.
func (is Intervals) Swap(i, j int) {
is[i], is[j] = is[j], is[i]
}
func merge(intervals []Interval) []Interval {
sort.Sort(Intervals(intervals))
if len(intervals) <= 1 {
return intervals
}
ans := make([]Interval, 0)
merging := intervals[0]
for _, v := range intervals[1:] {
if v.Start <= merging.End {
if v.End > merging.End {
merging.End = v.End
}
} else {
ans = append(ans, merging)
merging = v
}
}
ans = append(ans, merging)
return ans
}