-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathintervalset.go
74 lines (63 loc) · 1.53 KB
/
intervalset.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
67
68
69
70
71
72
73
74
package stats
import (
"sort"
)
// Interval represents a continous span.
type Interval struct {
Left int
Right int
}
func newInterval(left, right int) Interval {
return Interval{
Left: left,
Right: right,
}
}
// IntervalSet is a interval set.
type IntervalSet struct {
data []Interval
}
func newIntervalSet() *IntervalSet {
return &IntervalSet{}
}
// Insert inserts a new span.
func (iset *IntervalSet) Insert(left, right int) {
// skip the interval elemenets which are completely smaller than the new value.
n := len(iset.data)
i := sort.Search(len(iset.data), func(i int) bool {
return !(iset.data[i].Right < left)
})
if i == n {
iset.data = append(iset.data, newInterval(left, right))
return
}
intervals := make([]Interval, i, len(iset.data))
copy(intervals, iset.data[:i])
if left >= iset.data[i].Left {
left = iset.data[i].Left
}
for ; i < n; i++ {
if right < iset.data[i].Left {
intervals = append(intervals, newInterval(left, right))
intervals = append(intervals, iset.data[i:]...)
break
}
if right >= iset.data[i].Left && right <= iset.data[i].Right {
intervals = append(intervals, newInterval(left, iset.data[i].Right))
if i < n-1 {
intervals = append(intervals, iset.data[i+1:]...)
}
break
}
}
if i == n {
intervals = append(intervals, newInterval(left, right))
}
iset.data = intervals
}
// AllIntervals returns all intervals.
func (iset *IntervalSet) AllIntervals() []Interval {
intervals := make([]Interval, len(iset.data))
copy(intervals, iset.data)
return intervals
}