-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathmin_stack.rb
41 lines (35 loc) · 862 Bytes
/
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
# https://leetcode.com/problems/min-stack/
#
# Design a stack that supports push, pop, top, and retrieving the minimum
# element in constant time.
#
# + push(x) -- Push element x onto stack.
# + pop() -- Removes the element on top of the stack.
# + top() -- Get the top element.
# + getMin() -- Retrieve the minimum element in the stack.
class MinStack
# Initialize your data structure here
def initialize
@stack = []
@min_stack = []
end
# @param {Integer} x
# @return {Void} nothing
def push(x)
@stack.push(x)
@min_stack.push(x) if @min_stack.empty? || @min_stack[-1] >= x
end
# @return {Void} nothing
def pop
@min_stack.pop if @min_stack[-1] == @stack[-1]
@stack.pop; nil
end
# @return {Integer}
def top
@stack[-1]
end
# @return {Integer}
def get_min
@min_stack[-1]
end
end