Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
Implement the MinStack class:
MinStack()initializes the stack object.void push(val)pushes the elementvalonto the stack.void pop()removes the element on the top of the stack.int top()gets the top element of the stack.int getMin()retrieves the minimum element in the stack.
Example 1:
Input
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]
Output
[null,null,null,null,-3,null,0,-2]
Explanation
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); // return -3
minStack.pop();
minStack.top(); // return 0 minStack.getMin(); // return -2
想法:
這題要我們設計一個支援 push(), pop(), top(), getMin() 等操作的 stack 且各項操作的時間複雜度接須是 O(1) time。
push(), pop(), top() 實作都非常簡單利用 vector 或是 STL 內建的 stack 都可以輕鬆達成 O(1) 的要求,比較需要技巧的是 getMin(),如果說暴力搜索的話需要 O(n),因此需要用額外的一個 stack s_min 來儲存當前的最大值,跟主要存放資料的 stack s 不一樣,s_min 只有在當前 push 進來的值大於 s_min.top() 時才會真的 push,pop也是一樣只有當前 s.top() 剛好是目前最大值時才會真的pop,這樣利用兩個 stack 就可以同時紀錄資料與追蹤最大值。
完整程式碼:
/* two stack solution
* clever!!
*/
class MinStack {
public:
// normal stack
stack<int> s;
// record minimum value only
stack<int> s_min;
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
if (s_min.empty() || x <= this->getMin()) {
s_min.push(x);
}
s.push(x);
}
void pop() {
if (this->top() == this->getMin()) {
s_min.pop();
}
s.pop();
}
int top() {
return s.top();
}
int getMin() {
return s_min.top();
}
};
沒有留言:
張貼留言