-
Notifications
You must be signed in to change notification settings - Fork 376
/
min_stack_test.go
86 lines (66 loc) · 1.58 KB
/
min_stack_test.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
75
76
77
78
79
80
81
82
83
84
85
86
/*
Problem:
- Design a stack that supports push, pop, top, and retrieving the minimum element
in constant time.
Approach:
- We use two stack implementation themselves: one holds all the items and the
other holds all the minimum values after each push() and pop().
Cost:
- O(n) time, O(n) space.
*/
package leetcode
import (
"testing"
"github.com/hoanhan101/algo/common"
)
func TestMinStack(t *testing.T) {
s := newMinStack()
s.push(4)
common.Equal(t, 4, s.getMin())
s.push(8)
common.Equal(t, 4, s.getMin())
s.push(6)
common.Equal(t, 4, s.getMin())
s.push(2)
common.Equal(t, 2, s.getMin())
common.Equal(t, 2, s.pop())
common.Equal(t, 4, s.getMin())
common.Equal(t, 6, s.pop())
common.Equal(t, 4, s.getMin())
common.Equal(t, 8, s.pop())
common.Equal(t, 4, s.getMin())
common.Equal(t, 4, s.pop())
}
type minStack struct {
stack *common.Stack
minStack *common.Stack
}
func newMinStack() *minStack {
s := common.NewStack()
ms := common.NewStack()
return &minStack{
stack: s,
minStack: ms,
}
}
func (s *minStack) push(i int) {
// push the item on top of our stack.
s.stack.Push(i)
// only push the item to the minStack if it smaller or equal to the last
// item in minStack.
if s.minStack.Size() == 0 || i <= s.minStack.Top().(int) {
s.minStack.Push(i)
}
}
func (s *minStack) pop() int {
// pop the item of our stack.
i := s.stack.Pop().(int)
// if popped item is the smallest item, also remove that from minStack.
if i == s.minStack.Top().(int) {
s.minStack.Pop()
}
return i
}
func (s *minStack) getMin() int {
return s.minStack.Top().(int)
}