标签:
Min Stack
问题:
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
思路:
两个栈 一个正常栈,一个用来存储Min值
class MinStack { private Stack<Integer> normal = new Stack<Integer>(); private Stack<Integer> min = new Stack<Integer>(); public void push(int x) { if(min.isEmpty() || x <= min.peek()) { min.push(x); } normal.push(x); } public void pop() { int x = normal.pop(); if(x == min.peek()) { min.pop(); } } public int top() { return normal.peek(); } public int getMin() { return min.peek(); } }
标签:
原文地址:http://www.cnblogs.com/sunshisonghit/p/4338925.html