euisblue
155. Min Stack

C++

1class MinStack { 2 public: 3 stack<int> s1; 4 5 MinStack() {} 6 7 void push(int x) { 8 if(s1.empty()) { 9 s1.push(x); 10 s1.push(x); 11 } else { 12 int y = s1.top(); 13 s1.push(x); 14 s1.push((y<x) ? y : x); 15 } 16 } 17 18 void pop() { 19 s1.pop(); 20 s1.pop(); 21 } 22 23 int top() { 24 int x = s1.top(); 25 s1.pop(); 26 int y = s1.top(); 27 s1.push(x); 28 return y; 29 } 30 31 int getMin() { 32 return s1.top(); 33 } 34};

Ruby

1class MinStack 2 def initialize() 3 @stack = [] 4 @min = [] 5 end 6 7 def push(val) 8 @stack.push(val) 9 @min.push(val) if @min.empty? or val <= @min[-1] 10 end 11 12 def pop() 13 @min.pop if @stack[-1] == @min[-1] 14 @stack.pop 15 end 16 17 def top() 18 @stack[-1] 19 end 20 21 def get_min() 22 @min[-1] 23 end 24end