155. Min Stack

来源:互联网 发布:蒜泥白肉 知乎 编辑:程序博客网 时间:2024/06/07 21:49

1.题目
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.

2.分析
我可以说这道题我也做了好久么- -,首先我之前是使用一个list容器记录所有数值,当要取得当前栈在那个最小值时,进行遍历,按道理结果是没有问题,但是报了超时的错误,其实我觉得这个应该没有问题,18个测试用例通过了17个,但是当栈中有大量数据,并进行getMin操作比较频繁,这时候就会出现时间开销较高的问题。那么怎样减少时间开销呢,那就是将当前栈中最小的数值存储起来,使用一个辅助栈进行保存。

3.解题
我的解题:

 public class MinStack {/** initialize your data structure here. */Stack<Integer>stack;Stack<Integer>minstack;//ArrayList<Integer>list = new ArrayList<Integer>();int min = Integer.MAX_VALUE;public MinStack() {    stack = new Stack<Integer>();    minstack = new Stack<Integer>();}public void push(int x) {    stack.push(x);    if(minstack.isEmpty()||minstack.peek()>=x){        minstack.push(x);    }}public void pop() {    int num = stack.pop();    if(!minstack.isEmpty()&&num==minstack.peek()){        minstack.pop();    }    //list.remove(list.size()-1);}public int top() {    return stack.peek();}public int getMin() {    if(!minstack.isEmpty())    return minstack.peek();    return 0;}

}
解题中主要注意,就是当前put进去数值等于put操作之前最小数值时,也应该将其保存起来,不然会出现错误。

class MinStack {int min = Integer.MAX_VALUE;Stack<Integer> stack = new Stack<Integer>();public void push(int x) {    // only push the old minimum value when the current     // minimum value changes after pushing the new value x    if(x <= min){                  stack.push(min);        min=x;    }    stack.push(x);}public void pop() {    // if pop operation could result in the changing of the current minimum value,     // pop twice and change the current minimum value to the last minimum value.    if(stack.pop() == min) min=stack.pop();}public int top() {    return stack.peek();}public int getMin() {    return min;}}

说实话,这种解法我看了好久,想了好久,没想明白pop操作后,getMin结果为什么是对的?

4.总结
解题还是满需要花时间的,希望大家能够多多花时间思考,实在想不出问题的原因,可以借鉴别人的解题,但是一定要搞清楚,以及做好总结,做到举一反三。

原创粉丝点击