首页 > 代码库 > 155. Min Stack

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.

链接: http://leetcode.com/problems/min-stack/

2/18/2017, Java

注意!我们其实可以直接用stack不用ArrayList的!

Integer 和int是不相等的,第14行如果是Integer x = ...那么15行永远不相等!

 1 public class MinStack {
 2     ArrayList<Integer> list = new ArrayList<Integer>();
 3     ArrayList<Integer> min = new ArrayList<Integer>();
 4 
 5     /** initialize your data structure here. */
 6     public MinStack() {}
 7     
 8     public void push(int x) {
 9         list.add(x);
10         if (min.size() == 0 || x <= min.get(min.size() - 1)) min.add(x);
11     }
12 
13     public void pop() {
14         int x = list.remove(list.size() - 1);
15         if (x == min.get(min.size() - 1)) min.remove(min.size() - 1);
16     }
17     
18     public int top() {
19         return list.get(list.size() - 1);
20     }
21     
22     public int getMin() {
23         return min.get(min.size() - 1);
24     }
25 }

 

155. Min Stack