-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmerge.go
66 lines (55 loc) · 1.33 KB
/
merge.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
65
66
package mergeintervals
import "sort"
// Interval definition for an interval.
type Interval struct {
Start int
End int
}
// IntervalSlice slice of Interval
type IntervalSlice []Interval
// Len is the number of elements in the collection.
func (s IntervalSlice) Len() int {
return len(s)
}
// Less reports whether the element with
// index i should sort before the element with index j.
func (s IntervalSlice) Less(i, j int) bool {
return s[i].Start < s[j].Start
}
// Swap swaps the elements with indexes i and j.
func (s IntervalSlice) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func merge(intervals []Interval) []Interval {
if len(intervals) == 0 {
return []Interval{}
}
sort.Sort(IntervalSlice(intervals))
// a another sort scheme, faster in benchmark
//for keep := true; keep; {
// keep = false
// for i := 0; i < len(intervals)-1; i++ {
// if intervals[i].Start > intervals[i+1].Start {
// intervals[i], intervals[i+1] = intervals[i+1], intervals[i]
// keep = true
// }
// }
//}
res := make([]Interval, 0, len(intervals))
current := intervals[0]
for _, next := range intervals[1:] {
if next.Start <= current.End {
current.End = max(current.End, next.End)
} else {
res = append(res, current)
current = next
}
}
return append(res, current)
}
func max(x, y int) int {
if x >= y {
return x
}
return y
}