题目:定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
https://www.nowcoder.com/practice/4c776177d2c04c2494f2555c9fcc1e49
import java.util.Stack;
public class Solution {
private Stack<Integer> minStack = new Stack();
private Stack<Integer> normalStack = new Stack();
public void push(int node) {
normalStack.push(node);
if(minStack.isEmpty() || node<=minStack.peek()){
minStack.push(node);
}else{
minStack.push(minStack.peek());
}
}
public void pop() {
if(normalStack.isEmpty()) return;
normalStack.pop();
minStack.pop();
}
public int top() {
return normalStack.peek();
}
public int min() {
return minStack.peek();
}
}
网友评论