定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
注意:保证测试中不会当栈为空的时候,对栈调用pop()或者min()或者top()方法。
解析:方法①:用一个辅助栈:原栈正常push(); 辅助栈只push()比当前小的元素,如果不小于当前元素,则将当前元素再push()一遍;
方法②:方法①的优化:辅助栈只push最小值,及最小值相同值;当原栈与辅助栈,栈顶相同时,辅助栈才会pop()
代码:
方法①:
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<>();
Stack<Integer> stack2 = new Stack<>();
public void push(int node) {
stack1.push(node);
if(stack2.isEmpty() || stack2.peek() > node){
stack2.push(node);
}else{
stack2.push(stack2.peek());
}
}
public void pop() {
stack1.pop();
stack2.pop();
}
public int top() {
if(stack1.isEmpty()){
return 0;
}
return stack1.pop();
}
public int min() {
if(stack2.isEmpty()){
return 0;
}else{
return stack2.peek();
}
}
}
************************************************************************
方法②
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<>();
Stack<Integer> stack2 = new Stack<>();
public void push(int node) {
if(stack2.isEmpty() || stack2.peek() >= node){
stack2.push(node);
}
stack1.push(node);
}
public void pop() {
if(stack2.peek() == stack1.peek()){
stack2.pop();
}
stack1.pop();
}
public int top() {
if(stack1.isEmpty()){
return 0;
}
return stack1.pop();
}
public int min() {
if(stack2.isEmpty()){
return 0;
}else{
return stack2.peek();
}
}
}