首页 > 代码库 > 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。