-
Notifications
You must be signed in to change notification settings - Fork 252
/
min_stack.rb
121 lines (96 loc) · 1.95 KB
/
min_stack.rb
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
=begin
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
Implement the MinStack class:
MinStack() initializes the stack object.
void push(int val) pushes the element val onto the stack.
void pop() removes the element on the top of the stack.
int top() gets the top element of the stack.
int getMin() retrieves the minimum element in the stack.
You must implement a solution with O(1) time complexity for each function.
=end
#Solution 1 (Storing min with each node)
class MinStack
def initialize()
@stack = []
@min = ::Float::MAX
end
=begin
:type val: Integer
:rtype: Void
=end
def push(val)
@min = val if val<@min
@stack.push([val,@min])
end
=begin
:rtype: Void
=end
def pop()
val = @stack.pop
if @stack.empty?
@min = ::Float::MAX
else
@min = @stack[-1][1]
end
val[0]
end
=begin
:rtype: Integer
=end
def top()
@stack.last[0]
end
=begin
:rtype: Integer
=end
def get_min()
@min
end
end
# Your MinStack object will be instantiated and called as such:
# obj = MinStack.new()
# obj.push(val)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.get_min()
#Solution 2 (Using two stacks)
class MinStack
def initialize()
@stack = []
@min = []
end
=begin
:type val: Integer
:rtype: Void
=end
def push(val)
@min.push(val) if @min.empty? || val<=@min.last
@stack.push(val)
end
=begin
:rtype: Void
=end
def pop()
val = @stack.pop
@min.pop if @min.last==val
val
end
=begin
:rtype: Integer
=end
def top()
@stack.last
end
=begin
:rtype: Integer
=end
def get_min()
@min.last
end
end
# Your MinStack object will be instantiated and called as such:
# obj = MinStack.new()
# obj.push(val)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.get_min()