LeetCode——Min Stack
# 155
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.
这一题是让我们设计一个栈,支持push,pop,top,retrive the minimum element这几个操作。这一题是在考查对栈结构的掌握,主要是定义一个栈,其他的操作都是在此基础上进行的,比较需要用心的是取最小值这个操作,因为如果不单独设置这个操作,每次取最小值都要遍历整个栈。所以可以单独设置一个最小值栈,每次遇到更小的元素,则进栈,这样的话,经过push,pop后的取最小值,时间复杂度都为 O(1) 。
用stack定义两个栈。
- C++
class MinStack {
public:
/** initialize your data structure here. */
stack<int> sta;
stack<int> minstack;
MinStack() {
}
void push(int x) {
sta.push(x);
if(minstack.empty()) {
minstack.push(x);
}
else if(x <= minstack.top())
minstack.push(x);
}
void pop() {
if(sta.top() == minstack.top()) {
sta.pop();
minstack.pop();
}
else
sta.pop();
}
int top() {
return sta.top();
}
int getMin() {
return minstack.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();
*/
这里我的两个stack结构都是public范围,这样做题是可以的,但正确的应该是在private里定义。
C++,public、protected、private,简短总结:
1、public:类内、类的对象;派生类内、派生类对象—>>均可访问。
2、protected:类内、派生类内—>>可以访问;类的对象、派生类的对象–>>不可访问。
3、private:只有类内部–>>可以访问;类的对象、派生类、派生类的对象,统统的–>>不可访问。
Java的写法其实大同小异,写下来主要是熟悉Java的使用,这题就不用了,写个Python。
- Python
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.stack1 = []
self.stack2 = []
def push(self, x):
"""
:type x: int
:rtype: void
"""
self.stack1.append(x)
if len(self.stack2) == 0 or x <= self.stack2[-1]:
self.stack2.append(x)
def pop(self):
"""
:rtype: void
"""
top = self.stack1[-1]
self.stack1.pop()
if top == self.stack2[-1]:
self.stack2.pop()
def top(self):
"""
:rtype: int
"""
return self.stack1[-1]
def getMin(self):
"""
:rtype: int
"""
return self.stack2[-1]
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()
Python里面使用列表的结构来构造两个栈。
这一题的难点主要在于取最小元素。其他的都蛮简单的。