leetcode--Min Stack

来源:互联网 发布:focusky mac 破解版 编辑:程序博客网 时间:2024/06/06 05:28

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.
[java] view plain copy
  1. class MinStack {  
  2.     Stack<Integer> stack1 = new Stack<Integer>();  
  3.     Stack<Integer> stack2 = new Stack<Integer>();  
  4.       
  5.     public void push(int x) {     
  6.         if(stack2.size()==0||x<stack2.peek()){  
  7.             stack2.add(x);  
  8.         }else{  
  9.             stack2.add(stack2.peek());  
  10.         }  
  11.         stack1.add(x);  
  12.     }  
  13.   
  14.     public void pop() {  
  15.         stack2.pop();  
  16.         stack1.pop();  
  17.     }  
  18.   
  19.     public int top() {    
  20.         return stack1.peek();  
  21.     }  
  22.   
  23.     public int getMin() {  
  24.         return stack2.peek();  
  25.     }  
  26. }  

原文链接http://blog.csdn.net/crazy__chen/article/details/46383623

原创粉丝点击