码迷,mamicode.com
首页 > 其他好文 > 详细

155. Min Stack

时间:2017-02-19 10:47:00      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:str   tar   struct   removes   remove   ant   pop   new   array   

题目:

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

标签:str   tar   struct   removes   remove   ant   pop   new   array   

原文地址:http://www.cnblogs.com/panini/p/6414720.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!