创造min函数的栈
题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
注意:保证测试中不会当栈为空的时候,对栈调用pop()或者min()或者top()方法。
思路
使用双栈,一个存正常栈的顺序,一个存有序的顺序,只需要考虑 push 和pop 时的函数。
import java.util.Stack;
public class Solution {
Stack<Integer> stack = new Stack();
Stack<Integer> stack2 = new Stack();
Stack<Integer> temp = new Stack();
public void push(int node) {
stack.push(node);
if (stack2.size() == 0) {
stack2.push(node);
} else {
int size = stack2.size();
for (int i = 0; i <size; i++) {
if (stack2.peek() < node) {
temp.push(stack2.pop());
} else {
break;
}
}
stack2.push(node);
int tempSize = temp.size();
for (int i = 0; i <tempSize; i++) {
stack2.push(temp.pop());
}
}
}
public void pop() {
int node = stack.pop();
int size = stack2.size();
for(int i = 0; i < size; i++){
if(stack2.peek() == node){
stack2.pop();
break;
}else{
temp.push(stack2.pop());
}
}
int tempSize = temp.size();
for(int i = 0; i < tempSize; i++){
stack2.push(temp.pop());
}
}
public int top() {
return stack.peek();
}
public int min() {
return stack2.peek();
}
}