java——设计一个支持push,pop,top、在恒定时间内检索最小元素的栈。
普通方法:
需要另外一个栈 用来存放每一时刻的min值
巧妙版:
只需要一个stack,stack中存的是与min的差值
但由于min是两个整数之间的差值,有可能会出现差值超过整数边界值的情况,因此要变成Long型
import java.util.Stack; class MinStack { Stack<Long> stack; long min; /** initialize your data structure here. */ public MinStack() { stack = new Stack<>(); } public void push(int x) { if(stack.isEmpty()){ stack.push(0L); min = x; }else { stack.push(x - min); if (x < min) { min = x; } } } public void pop() { if(stack.isEmpty()){ return; } Long temp = stack.pop(); if(temp<0){ min = min - temp; } } public int top() { Long top = stack.peek(); if (top > 0) { return (int)(stack.peek()+min); } return (int)min; } public int getMin() { return (int)min; } } /** * 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(); */