您的位置:首页 > 其它

[LintCode] 带最小值操作的栈 Min Stack

2016-04-22 15:48 344 查看
实现一个带有取最小值min方法的栈,min方法将返回当前栈中的最小值。

你实现的栈将支持push,pop 和 min 操作,所有操作要求都在O(1)时间内完成。

样例

如下操作:push(1),pop(),push(2),push(3),min(), push(1),min() 返回 1,2,1

Implement a stack with min() function, which will return the smallest number in the stack.

It should support push, pop and min operation all in O(1) cost.

Notice

min operation will never be called if there is no number in the stack.

Example

push(1)

pop() // return 1

push(2)

push(3)

min() // return 2

push(1)

min() // return 1

参考:/article/3642055.html

/article/3642055.html

public class MinStack {
Stack<Integer> stack;
int min;
public MinStack() {
stack = new Stack<Integer>();
min = 0;
}

public void push(int number) {
if(stack.size() == 0) {
stack.push(number);
min = number;
} else{
if(number >= min) {
stack.push(number);
}else {
stack.push(2*number - min);
min = number;
}
}
}

public int pop() {
if(!stack.isEmpty()) {
int temp = stack.pop();
if(temp < min) {
int num = min;
min = 2*min - temp;
temp = num;
}
return temp;
}else {
return min;
}

}

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