题目描述
设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。
push(x) – 将元素 x 推入栈中。
pop() – 删除栈顶的元素。
top() – 获取栈顶元素。
getMin() – 检索栈中的最小元素。
总结
略看SDC1的时候感觉getMin()有问题,但其实push()和pop()写的很巧妙
比如依次录入5,4,3,2这组数据后,栈的数据为
MAX,5,__5,4,__4,3,_3,2
往前数组中第二小的数,往前数组中最小的数
SDC2用的一个辅助栈,与数据栈同步记录
Sample & Demo Code 1
class MinStack {
int min = Integer.MAX_VALUE;
private Stack<Integer> stack ;
public MinStack() {
stack = new Stack<Integer>();
}
public void push(int x) {
if(x <= min){
stack.push(min);
min=x;
}
stack.push(x);
}
public void pop() {
if(stack.pop() == min) min=stack.pop();
}
public int top() {
return stack.peek();
}
public int getMin() {
return min;
}
}
Sample & Demo Code 2
class MinStack {
/** initialize your data structure here. */
private int[] s;
private int[] min;
private int top;
public MinStack() {
s = new int[10];
min = new int[10];
top = -1;
}
public void push(int x) {
if (top == s.length-1) {
int[] temps = new int [s.length*2];
int[] tempm = new int [s.length*2];
for (int i = 0; i < s.length; i++){
temps[i] = s[i];
tempm[i] = min[i];
}
s = temps;
min = tempm;
}
s[top+1] = x;
if (top < 0)
min[top+1] = x;
else
min[top+1] = x < min[top] ? x : min[top];
top++;
}
public void pop() {
if (top >= 0) top--;
}
public int top() {
if (top >= 0)
return s[top];
else
return -1;
}
public int getMin() {
return min[top];
}
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/min-stack