03.02. 栈的最小值
请设计一个栈,除了常规栈支持的pop与push函数以外,还支持min函数,该函数返回栈元素中的最小值。执行push、pop和min操作的时间复杂度必须为O(1)。
示例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.
class MinStack {
Deque<Integer> s;
Deque<Integer> m;
/** initialize your data structure here. */
public MinStack() {
s=new LinkedList<Integer>();
m=new LinkedList<Integer>();
}
public void push(int x) {
if(m.isEmpty())
{
m.push(x);
}else
{
int y=x<m.peek()?x:m.peek();
m.push(y);
}
s.push(x);
}
public void pop() {
s.pop();
m.pop();
}
public int top() {
return s.peek();
}
public int getMin() {
return m.peek();
}
}
/**
* 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();
*/
个人总结: 发现最大的问题不是做题,而是审题。
03.04. 化栈为队
实现一个MyQueue类,该类用两个栈来实现一个队列。
示例:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // 返回 1
queue.pop(); // 返回 1
queue.empty(); // 返回 false
class MyQueue {
Deque<Integer> instack;
Deque<Integer> outstack;
/** Initialize your data structure here. */
public MyQueue() {
instack=new LinkedList<Integer>();
outstack=new LinkedList<Integer>();
}
/** Push element x to the back of queue. */
public void push(int x) {
instack.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
int x=peek();
outstack.pop();
return x;
}
/** Get the front element. */
public int peek() {
if(outstack.isEmpty()&&!instack.isEmpty())
{
while(!instack.isEmpty())
{
outstack.push(instack.peek());
instack.pop();
}
}
return outstack.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return instack.isEmpty()&&outstack.isEmpty();
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/
个人总结: 之前做过,两个栈,只在出栈空时将入栈内容倒入出栈。