# 【LeetCode】 155. Min Stack ## Description > 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. > 請設計一個stack支援push, pop, top和回傳最小值。 > - push(x) -- 將x放入stack裡面。 > - pop() -- 把最上面的元素移除。 > - top() -- 得到最上面的元素。 > - getMin() -- 把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. ``` ## Solution * 直接使用STL裡面的vector即可。 * 當然你也可以嘗試自己刻一個stack,可以用linked list之類的。 ### Code ```C++=1 class MinStack { public: /** initialize your data structure here. */ vector<int> data; int dataMin; MinStack() { dataMin=INT_MAX; } void push(int x) { data.push_back(x); dataMin = min(dataMin,x); } void pop() { if(dataMin == data.back()) { dataMin=INT_MAX; data.pop_back(); for(int i=0;i<data.size();i++) dataMin = min(dataMin,data[i]); } else data.pop_back(); } int top() { return data.back(); } int getMin() { return dataMin; } }; /** * 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(); */ ``` ###### tags: `LeetCode` `C++`
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up