155. Min Stack / Min Stack
leet和lint不太一样,leet多一个top()。但实现是一样的。
minStack只能用两个stack实现,不能用别的。
public class MinStack {
private Stack<Integer> stack;
private Stack<Integer> minStack;
/** initialize your data structure here. */
public MinStack() {
stack = new Stack<>();
minStack = new Stack<>();
}
public void push(int x) {
stack.push(x);
if (minStack.isEmpty()) {
minStack.push(x);
} else minStack.push(Math.min(x, minStack.peek()));
}
public void pop() {
minStack.pop();
stack.pop();
}
public int top() {
return stack.peek();
}
public int getMin() {
return minStack.peek();
}
}
在上面这种实现中,我们实际上push到minStack中很多冗余的元素,下面的解法可以节省一定的空间,但两者的空间复杂度是相同的。
public class MinStack {
private Stack<Integer> stack;
private Stack<Integer> minStack;
public MinStack() {
stack = new Stack<Integer>();
minStack = new Stack<Integer>();
}
public void push(int number) {
stack.push(number);
if (minStack.empty() == true)
minStack.push(number);
else {
// 这里考虑的相等的情况也会继续push
if (minStack.peek() >= number)
minStack.push(number);
}
}
public int pop() {
if (stack.peek().equals(minStack.peek()) )
minStack.pop();
return stack.pop();
}
public int min() {
return minStack.peek();
}
}
232. Implement Queue using Stacks
年少无知时第一次做这题,拿两个stack底部相接,妄图拼出一个queue来。现在想起来简直笑出声。
public class MyQueue {
private Stack<Integer> stack1;
private Stack<Integer> stack2;
/** Initialize your data structure here. */
public MyQueue() {
stack1 = new Stack<>();
stack2 = new Stack<>();
}
private void stack2To1() {
while (!stack2.isEmpty()) {
stack1.push(stack2.pop());
}
}
/** Push element x to the back of queue. */
public void push(int x) {
stack2.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
if (stack1.isEmpty()) {
this.stack2To1();
}
return stack1.pop();
}
/** Get the front element. */
public int peek() {
if (stack1.isEmpty()) {
this.stack2To1();
}
return stack1.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
return (stack1.isEmpty() && stack2.isEmpty());
}
}
225. Implement Stack using Queues
public class MyStack {
private Queue<Integer> queue1;
private Queue<Integer> queue2;
/** Initialize your data structure here. */
public MyStack() {
queue1 = new LinkedList<>();
queue2 = new LinkedList<>();
}
private void move() {
while (queue1.size() != 1) {
queue2.offer(queue1.poll());
}
}
private void swap() {
Queue<Integer> tmp = queue1;
queue1 = queue2;
queue2 = tmp;
}
/** Push element x onto stack. */
public void push(int x) {
queue1.offer(x);
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
move();
int item = queue1.poll();
swap();
return item;
}
/** Get the top element. */
public int top() {
move();
int item = queue1.poll();
swap();
queue1.offer(item);
return item;
}
/** Returns whether the stack is empty. */
public boolean empty() {
return queue1.isEmpty();
}
}