题目:155. 最小栈
思路:栈,时间复杂度0(n)。
在插入栈元素val时,同时加入一个字段,维护插入当前元素val时的最小值即可。
C++版本:
cpp
class MinStack {
public:
stack<pair<int,int>> st;
MinStack() {
// 哨兵
st.push({0,INT_MAX});
}
void push(int val) {
st.push({val,min(getMin(),val)});
}
void pop() {
st.pop();
}
int top() {
return st.top().first;
}
int getMin() {
return st.top().second;
}
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack* obj = new MinStack();
* obj->push(val);
* obj->pop();
* int param_3 = obj->top();
* int param_4 = obj->getMin();
*/
JAVA版本:
java
class MinStack {
private final Deque<int[]> st=new ArrayDeque<>();
public MinStack() {
st.push(new int[]{0,Integer.MAX_VALUE});
}
public void push(int val) {
st.push(new int[]{val,Math.min(getMin(),val)});
}
public void pop() {
st.pop();
}
public int top() {
return st.peek()[0];
}
public int getMin() {
return st.peek()[1];
}
}
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(val);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/
GO版本:
go
type PII struct {
x int
y int
}
type MinStack struct {
st []PII
}
func Constructor() MinStack {
return MinStack{[]PII{{0,math.MaxInt}}}
}
func (this *MinStack) Push(val int) {
this.st=append(this.st,PII{val,min(this.GetMin(),val)})
}
func (this *MinStack) Pop() {
this.st=this.st[:len(this.st)-1]
}
func (this *MinStack) Top() int {
return this.st[len(this.st)-1].x
}
func (this *MinStack) GetMin() int {
return this.st[len(this.st)-1].y
}
/**
* Your MinStack object will be instantiated and called as such:
* obj := Constructor();
* obj.Push(val);
* obj.Pop();
* param_3 := obj.Top();
* param_4 := obj.GetMin();
*/