您的位置:首页 > 其它

Min Stack

2015-08-03 17:18 309 查看
</pre><p style="margin-top:0px; margin-bottom:10px; color:rgb(51,51,51); font-family:'Helvetica Neue',Helvetica,Arial,sans-serif; font-size:14px; line-height:30px">Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.</p><ul style="margin-top:0px; margin-bottom:10px; color:rgb(51,51,51); font-family:'Helvetica Neue',Helvetica,Arial,sans-serif; font-size:14px; line-height:30px"><li style="">push(x) -- Push element x onto stack.</li><li style="">pop() -- Removes the element on top of the stack.</li><li style="">top() -- Get the top element.</li><li style="">getMin() -- Retrieve the minimum element in the stack.</li></ul><p></p><p>思路:关键点在于获取最小值,一般的方法就是遍历整个容器,除非容器是有序的;但是栈本身无法实现在不影响他本身的情况下遍历,除非不断抛出最上方的元素,所以需要有一个额外的容器来存储每次栈中的元素,然后遍历他来找到最小值。</p><p></p><p><pre name="code" class="java">class MinStack {
Stack<Integer> stack=new Stack<>();
List<Integer> list=new ArrayList<>();
public void push(int x) {
stack.push(x);
list.add(x);
}

public void pop() {
stack.pop();
list.remove(list.size()-1);
}

public int top() {
return stack.peek();
}

public int getMin() {
int min=list.get(0); //注意将最小值设为第一位
for(int i=0;i<list.size();i++){
if(min>list.get(i)) min=list.get(i);
}
return min;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: