Leetcode 155: 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.
Example:
MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); --> Returns -3. minStack.pop(); minStack.top(); --> Returns 0. minStack.getMin(); --> Returns -2.
1 public class MinStack { 2 private Stack<int> stack; 3 private Stack<int> minStack; 4 5 /** initialize your data structure here. */ 6 public MinStack() { 7 this.stack = new Stack<int>(); 8 this.minStack = new Stack<int>(); 9 } 10 11 public void Push(int x) { 12 this.stack.Push(x); 13 14 if (this.minStack.Count == 0 || x <= this.minStack.Peek()) 15 { 16 this.minStack.Push(x); 17 } 18 } 19 20 public void Pop() { 21 if (this.stack.Count > 0) 22 { 23 var top = this.stack.Pop(); 24 if (this.minStack.Peek() == top) 25 { 26 this.minStack.Pop(); 27 } 28 } 29 } 30 31 public int Top() { 32 return this.stack.Peek(); 33 } 34 35 public int GetMin() { 36 return this.minStack.Peek(); 37 } 38 } 39 40 /** 41 * Your MinStack object will be instantiated and called as such: 42 * MinStack obj = new MinStack(); 43 * obj.Push(x); 44 * obj.Pop(); 45 * int param_3 = obj.Top(); 46 * int param_4 = obj.GetMin(); 47 */

浙公网安备 33010602011771号