LeetCode155 - 最小栈
作者:互联网
LeetCode155 - 最小栈(难度:简单)
链接:https://leetcode-cn.com/problems/min-stack
设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。
push(x) —— 将元素 x 推入栈中。
pop() —— 删除栈顶的元素。
top() —— 获取栈顶元素。
getMin() —— 检索栈中的最小元素。
示例:
输入:
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]
输出:
[null,null,null,null,-3,null,0,-2]
解释:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.
编码:
class MinStack {
private Stack<Integer> minStack;
private int[] elements;
private int size;
/** initialize your data structure here. */
public MinStack() {
this.minStack = new Stack<>();
this.size = 0;
this.elements = new int[0];
}
public void push(int val) {
ensureCapcity();
this.elements[size++] = val;
if(this.minStack.isEmpty() || this.minStack.peek() >= val) {
this.minStack.push(val);
}
}
private void ensureCapcity() {
if(this.elements.length < size+1){
// int[] newArray = new int[size + size/2];
int[] newArray = Arrays.copyOf(this.elements, size+1);
// System.arrayCopy(elements, newArray);
this.elements = newArray;
}
}
public void pop() {
int peekVal = top();
if(this.minStack.peek() == peekVal) {
this.minStack.pop();
}
this.elements[--size] = 0;
}
public int top() {
return this.elements[size-1];
}
public int getMin() {
return this.minStack.peek();
}
}
标签:LeetCode155,minStack,int,最小,pop,elements,push,size 来源: https://blog.csdn.net/Juwenzhe_HEBUT/article/details/115497111