队列&栈//最小栈
设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。
- push(x) -- 将元素 x 推入栈中。
- pop() -- 删除栈顶的元素。
- top() -- 获取栈顶元素。
- getMin() -- 检索栈中的最小元素。
示例:
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> s1 = new Stack<>();
private Stack<Integer> s2 = new Stack<>();
/** initialize your data structure here. */
public MinStack() {
}
public void push(int x) {
s1.push(x);
if(s2.isEmpty()||s2.peek()>=x)
s2.push(x);
}
public void pop() {
int x = s1.pop();
if(s2.peek()==x)
s2.pop();
}
public int top() {
return s1.peek();
}
public int getMin() {
return s2.peek();
}
}
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(x);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/
class MinStack {
private int min_val = Integer.MAX_VALUE;
private Stack<Integer> s = new Stack<>();
/** initialize your data structure here. */
public MinStack() {
}
public void push(int x) {
if(x <= min_val){
s.push(min_val);
min_val = x;
}
s.push(x);
}
public void pop() {
if(s.pop()==min_val)
min_val = s.pop();
}
public int top() {
return s.peek();
}
public int getMin() {
return min_val;
}
}
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(x);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/
class MinStack {
private:
stack<int> s1,s2;
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
s1.push(x);
if(s2.empty()||x<=s2.top())
s2.push(x);
}
void pop() {
if(s1.top()==s2.top())
s2.pop();
s1.pop();
}
int top() {
return s1.top();
}
int getMin() {
return s2.top();
}
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(x);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/
class MinStack {
public:
/** initialize your data structure here. */
MinStack() {
min_val = INT_MAX;
}
void push(int x) {
if(x <= min_val)
{
st.push(min_val);
min_val = x;
}
st.push(x);
}
void pop() {
int t = st.top();
st.pop();
if(t == min_val){
min_val = st.top();
st.pop();
}
}
int top() {
return st.top();
}
int getMin() {
return min_val;
}
private:
int min_val;
stack<int> st;
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(x);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/