您的位置:首页 > 其它

Min Stack

2016-07-09 07:59 190 查看
Implementastackwithmin()function,whichwillreturnthesmallestnumberinthestack.

Itshouldsupportpush,popandminoperationallinO(1)cost.

Notice

minoperationwillneverbecalledifthereisnonumberinthestack.

Example

push(1)
pop()//return1
push(2)
push(3)
min()//return2
push(1)
min()//return1

分析:
用另一个stack来保存当前最小的值。


publicclassMinStack{

Stack<Integer>elements=newStack<Integer>();
Stack<Integer>minStack=newStack<Integer>();

publicMinStack(){
//doinitializeifnecessary
}

publicvoidpush(intx){
elements.push(x);
if(minStack.isEmpty()||x<=minStack.peek()){
minStack.push(x);
}
}

publicintpop(){
if(elements.isEmpty()){
return-1;
}
//这个地方太蛋疼了,居然要用equals...
if(elements.peek().equals(minStack.peek())){
minStack.pop();
}
returnelements.pop();
}

publicintmin(){
returnminStack.peek();
}
}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: