算法设计与应用基础系列14

来源:互联网 发布:mac开机客人用户 编辑:程序博客网 时间:2024/06/05 10:00

Min Stack


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.
设计一个栈,支持推,弹出,顶部,并在常量时间检索最小元素。
推(x)-将元素X推到堆栈上。
pop() --删除栈顶元素。
top() --获得顶级元素。
getmin()检索堆栈中的最小元素。


对栈有所了解的话这题算是非常非常简单的题目了!! 通过简单的几行代码即可实现,关键是要弄懂栈函数的功能

public int evalRPN(String[] tokens) {    return helper(tokens, new RefInt(tokens.length-1));}int helper(String[] tokens, RefInt top){    String t = tokens[top.val];    top.val--;    if(t.equals("+") || t.equals("-") || t.equals("*") || t.equals("/"))    {        int n0 = helper(tokens, top);        int n1 = helper(tokens, top);        if (t.equals("+")) return n1+n0;        else if(t.equals("-")) return n1-n0;        else if(t.equals("*")) return n1*n0;        else return n1/n0;    }    else{        return Integer.valueOf(t);    }}
原创粉丝点击