實現一個棧,使其push,pop,min(取得棧中的最小元素)均為O(1)
實現一個棧,使其push,pop,min(取得棧中的最小元素)均為O(1)
我的解
interface IntStack


{
int pop();
void push(int i);
int get();
}

class MinStack


{
//store all the element
private IntStack elemStack = new IntStack();
//store current and historical smallest element
private IntStack minStack = new IntStack();
public void push(int i)

{
elemStack.push(i);
int currentMin = minStack.get();
if(i <= currentMin) minStack.push(i);
}
public int pop()

{
int result = elemStack.pop();
if(result == minStack.get()) minStack.pop();
return result;
}
public int getMinElem()

{
return minStack.get();
}
}
我的解













































posted @ 2007-07-18 20:57 Job Hu 閱讀(902) | 評論 (0) | 編輯 收藏