Min Stack(155)
阿新 • • 發佈:2018-12-28
155— Min Stack
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
- push(x) – Push element x onto stack.
- pop() – Removes the element on top of the stack.
- top() – Get the top element.
- getMin() – Retrieve the minimum element in the stack.
Example:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> Returns -3.
minStack.pop();
minStack.top(); --> Returns 0.
minStack.getMin(); --> Returns -2.
C++程式碼:
class MinStack {
public:
/** initialize your data structure here. */
void push(int x) {
v.push_back(x);
}
void pop() {
v.pop_back();
}
int top() {
return v.back();
}
int getMin() {
int len = v.size();
int min = v[0];
for(int i = 1; i < len;i++) {
if(v[i] < min) min = v[i];
}
return min;
}
private:
vector<int> v;
};
思路1:
- 簡單的棧的應用, 遍歷一下vector元素即可
思路2:
- 一般思路是用一個變數min記錄當前最小, 但如果當前最小的元素出棧, 沒辦法記錄min 為出棧後第一小的元素(即出棧前第二小的元素)
- 使用另一個vector min記錄最小元素, 棧頂元素為當前最小
- 當vector出棧一個元素, 如果為當前最小, min 出棧, 此次 min的棧頂仍然為當前最小元素
C++程式碼:
class MinStack {
public:
/** initialize your data structure here. */
void push(int x) {
v.push_back(x);
if(min.empty() || x <= min.back()) min.push_back(x);
}
void pop() {
if(v.back() == min.back()) min.pop_back();
v.pop_back();
}
int top() {
return v.back();
}
int getMin() {
return min.back();
}
private:
vector<int> v;
vector<int> min;;
};