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

 

解答:

 1 public class MinStack {
 2     private Stack<Integer> stack = new Stack<>();
 3     private Stack<Integer> minStack = new Stack<>();
 4 
 5     public void push(int x) {
 6         stack.push(x);
 7         if(minStack.isEmpty() || x <= minStack.peek()) {
 8             minStack.push(x);
 9         }
10     }
11 
12     public void pop() {
13         if(stack.pop().equals(minStack.peek())) {
14             minStack.pop();
15         }
16     }
17 
18     public int top() {
19         return stack.peek();
20     }
21 
22     public int getMin() {
23         return minStack.peek();
24     }
25 }

 

posted @ 2019-02-24 15:19  林木声  阅读(109)  评论(0编辑  收藏  举报