-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmonotonic_stack.go
More file actions
49 lines (40 loc) · 768 Bytes
/
monotonic_stack.go
File metadata and controls
49 lines (40 loc) · 768 Bytes
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
package priorityqueue
type stack struct {
/*
[] - slice with intervals
[2] - array with start and end intervals
*/
idx [][2]int
}
func newStack() *stack {
return &stack{
idx: make([][2]int, 0, 10),
}
}
func (st *stack) Add(idx int) {
/*
we have to store the beginning of the range + the last
*/
// st.intervals[len(st.intervals)-1][1] - last seen interval
// firstly seen
if len(st.idx) == 0 {
st.idx = append(st.idx, [2]int{
idx, idx,
})
return
}
// last[1] is a previously added element
if st.idx[len(st.idx)-1][1]+1 == idx {
st.idx[len(st.idx)-1][1] = idx
return
}
st.idx = append(st.idx, [2]int{
idx, idx,
})
}
func (st *stack) Indices() [][2]int {
return st.idx
}
func (st *stack) clear() {
st.idx = st.idx[:0]
}