今天的题目 每天的题目见github(看最新的日期): https://github.com/gzc426 具体的题目可以去牛客网对应专题去找。
每天一道剑指offer-包含min函数的栈 来源:牛客网对应专题
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
思路
代码
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.empty())
{
stack2.push(node);
}else{
if(node <= (int)stack2.peek()) //这个if/else是比较栈顶与入栈的值,哪个小入哪个
stack2.push(node);
else{
stack2.push(stack2.peek());
}
}
}
public void pop() {
stack2.pop();//出栈是都出栈的
stack1.pop();
}
public int top() {
return (int)stack1.peek();
}
public int min() {
return (int)stack2.peek();//栈2是辅助栈,每次都是最小值
}
}
代码截图(避免乱码)